UIView drawInRect 与 UIImage 导致黑色背景

Ale*_*Lee 3 iphone objective-c uiview uiimage ios

我有以下代码:

@implementation MyImageView
@synthesize image; //image is a UIImage
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
    // Initialization code

}
return self;
}
-(void) removeFromSuperview
{
self.image = nil;
[super removeFromSuperview];
}


- (void)drawRect:(CGRect)rect
{
// Drawing code
if (self.image)
{

    CGContextRef context = UIGraphicsGetCurrentContext();


    CGContextClearRect(context, rect);
    //the below 2 lines is to prove that the alpha channel of my UIImage is indeed drawn
    //CGContextSetFillColorWithColor(context, [UIColor whiteColor].CGColor);
    //CGContextFillRect(context, rect);
    CGContextDrawImage(context, self.bounds, self.image.CGImage);


}
}
@end
Run Code Online (Sandbox Code Playgroud)

当我运行代码时,我意识到我的视图的背景是黑色的。为了测试我的 UIImage 是否有问题,我使用了 CGContextClearRect(context, rect) 之后注释的两行。确实绘制了白色背景。无论如何,我可以删除黑色背景吗?当我初始化MyImageView时,我已经将backgroundColor设置为[UIColor clearColor]。

非常感谢任何建议。谢谢

Mik*_*ler 5

将背景颜色设置为[UIColor clearColor]应该可以。还设置self.opaque = NO为启用透明度。

您还应该检查是否调用了正确的初始化程序。例如,如果视图是 XIB 文件的一部分,您需要实现initWithCoder:以及initWithFrame:等等。