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]。

非常感谢任何建议。谢谢

4

3 回答 3

4

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

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

于 2012-06-20T11:34:42.817 回答
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()
于 2016-03-17T16:36:03.863 回答
0

无论如何,您的 CGContext 都会颠倒过来,所以只需走简单的路线并使用

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

反而。

于 2012-06-20T11:23:38.563 回答