繁体   English   中英

UIView drawInRect与UIImage导致blackbackground

[英]UIView drawInRect with UIImage results in blackbackground

我有以下代码:

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

任何建议都非常感谢。 谢谢

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

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

我有同样的问题 - 这对我有用(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()

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

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

代替。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM