【问题标题】:UIView drawInRect with UIImage results in blackbackgroundUIView draw Rect with Image 结果为黑色背景
【发布时间】:2012-06-20 11:18:58
【问题描述】:

我有以下代码:

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

非常感谢任何建议。 谢谢

【问题讨论】:

  • 为什么不取消注释这两行?
  • 当我取消注释这两行时,我的背景将是白色的。我需要图像的 alpha 与背景混合
  • 哦,好的,是的,你现在我明白了

标签: iphone objective-c ios uiview uiimage


【解决方案1】:

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

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

【讨论】:

  • 谢谢。我以为我已经设置好了。原来我没有为我的测试用例做这件事。虚惊一场,谢谢你的建议。
  • 你在哪里设置背景。我在属性字符串中使用我的图像而不是 UIImageView
【解决方案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()

【讨论】:

    【解决方案3】:

    您的 CGContext 将上下颠倒 无论如何,所以只要走简单的路线并使用

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

    相反。

    【讨论】:

    • 那是我的原始代码。它也没有奏效。够奇怪了,我现在的代码并没有倒过来画……
    猜你喜欢
    • 2013-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-30
    • 2011-09-19
    • 1970-01-01
    • 1970-01-01
    • 2013-12-12
    相关资源
    最近更新 更多