合成UIImages时,Image Context会产生伪影

时间:2010-02-20 07:48:45

标签: objective-c cocoa-touch uikit uiimage

我正在尝试在基本图像上叠加自定义半透明图像。叠加图像是可伸缩的,并按如下方式创建:

[[UIImage imageNamed:@"overlay.png"] stretchableImageWithLeftCapWidth:5.0 topCapHeight:5.0]

然后我将其传递给一个方法,将其覆盖在背景图像上以获取按钮:

- (void)overlayImage:(UIImage *)overlay forState:(UIControlState)state {
    UIImage *baseImage = [self backgroundImageForState:state];      

    CGRect frame = CGRectZero;
    frame.size = baseImage.size;

    // create a new image context
    UIGraphicsBeginImageContext(baseImage.size);        

    // get context
    CGContextRef context = UIGraphicsGetCurrentContext();   

    // clear context
    CGContextClearRect(context, frame);

    // draw images
    [baseImage drawInRect:frame];   
    [overlay drawInRect:frame];// blendMode:kCGBlendModeNormal alpha:1.0];

    // get UIImage
    UIImage *overlaidImage = UIGraphicsGetImageFromCurrentImageContext();

    // clean up context
    UIGraphicsEndImageContext();

    [self setBackgroundImage:overlaidImage forState:state];
}

生成的overlayidImage看起来大部分都是正确的,它是正确的大小,alpha正确混合等等。但是它有垂直的伪像/噪音。

UIImage artifacts example http://acaciatreesoftware.com/img/UIImage-artifacts.png

(例如http://acaciatreesoftware.com/img/UIImage-artifacts.png

我首先尝试清除上下文,然后关闭PNG压缩 - 这减少了一些伪像(完全在我认为的非拉伸图像上)。

有没有人知道一种绘制可伸缩UIImages的方法,而不会发生这种伪影?

2 个答案:

答案 0 :(得分:0)

所以答案是:不要这样做。相反,您可以在程序上绘制叠加层。像这样:

- (void)overlayWithColor:(UIColor *)overlayColor forState:(UIControlState)state {
    UIImage *baseImage = [self backgroundImageForState:state];      

    CGRect frame = CGRectZero;
    frame.size = baseImage.size;

    // create a new image context
    UIGraphicsBeginImageContext(baseImage.size);        

    // get context
    CGContextRef context = UIGraphicsGetCurrentContext();   

    // draw background image
    [baseImage drawInRect:frame];   

    // overlay color
    CGContextSetFillColorWithColor(context, [overlayColor CGColor]);
    CGContextSetBlendMode(context, kCGBlendModeSourceAtop);
    CGContextFillRect(context, frame);

    // get UIImage
    UIImage *overlaidImage = UIGraphicsGetImageFromCurrentImageContext();

    // clean up context
    UIGraphicsEndImageContext();

    [self setBackgroundImage:overlaidImage forState:state];
}

答案 1 :(得分:0)

你是否过于吝啬原始图像,并强迫它伸展而不是缩小?我已经找到了符合相同宽高比并且尺寸减小的图像的最佳结果。可能无法解决你的问题。

相关问题