UIView在UIImage中使用drawInRect导致黑色背景

3

我有以下代码:

@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

当我运行代码时,我发现我的视图的背景是黑色的。为了测试是否是我的UIImage的问题,我使用了在CGContextClearRect(context,rect)后注释的2行代码。确实绘制了白色背景。有没有办法让我去掉黑色背景?当我初始化MyImageView时,我已经将backgroundColor设置为[UIColor clearColor]。
非常感谢任何建议。谢谢。

为什么不只是取消注释这两行代码呢? - Omar Abdelhafith
当我取消注释这两行时,我的背景将变为白色。我需要图像的 alpha 与背景混合。 - Alexander Lee
哦,好的,是的,你说得对,现在我明白了。 - Omar Abdelhafith
3个回答

5

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

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


谢谢。我以为我已经设置好了,结果发现我没有为我的测试用例做到这一点。虚惊一场,感谢你的建议。 - Alexander Lee
1
你在哪里设置背景?我正在使用属性字符串中的图像,而不是UIImageView。 - Michal Shatz

2
我遇到了同样的问题 - 这个方法对我有用(Swift示例)
    var backgroundImage = UIImage() //background image - size = 100x100
    var frontImage = UIImage()  //smaller image to be drawn in the middle

    UIGraphicsBeginImageContextWithOptions(CGSizeMake(100, 100), false, 0.0) //false here indicates transparent

    var context = UIGraphicsGetCurrentContext()!

    UIGraphicsPushContext(context)

    backgroundImage.drawInRect(CGRectMake(0, 0, 100, 100))
    frontImage.drawInRect(CGRectMake((100 - frontImage.size.width) / 2, (diameter - frontImage.size.height) / 2, frontImage.size.width, frontImage.size.height))

    UIGraphicsPopContext()

    var outputImage = UIGraphicsGetImageFromCurrentImageContext()

    UIGraphicsEndImageContext()

0

无论如何,您的CGContext都会向下绘制,因此只需走捷径并使用以下代码:

[self.image drawInRect:CGRectMake(rect)]; 

相反。


那是我的原始代码。它没有很好地工作。奇怪的是,我的当前代码没有倒置绘制... - Alexander Lee

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接