如何平滑绘制图像的边缘?

时间:2012-08-08 20:04:43

标签: ios uiimage core-graphics cgcontext cgimage

我正在使用此代码来着色UIButton子类的一些图像:

UIImage *img = [self imageForState:controlState];

// begin a new image context, to draw our colored image onto
UIGraphicsBeginImageContextWithOptions(img.size, NO, 0.0f);
// get a reference to that context we created
CGContextRef context = UIGraphicsGetCurrentContext();

// set the fill color
[self.buttonColor setFill];

CGContextSetAllowsAntialiasing(context, true);
CGContextSetShouldAntialias(context, true);

// translate/flip the graphics context (for transforming from CG* coords to UI* coords
CGContextTranslateCTM(context, 0, img.size.height);
CGContextScaleCTM(context, 1.0, -1.0);

// set the blend mode to multiply, and the original image
CGContextSetBlendMode(context, kCGBlendModeScreen);
CGRect rect = CGRectMake(0, 0, img.size.width, img.size.height);
CGContextDrawImage(context, rect, img.CGImage);

// set a mask that matches the shape of the image, then draw the colored image
CGContextClipToMask(context, rect, img.CGImage);
CGContextAddRect(context, rect);
CGContextDrawPath(context,kCGPathFill);

// generate a new UIImage from the graphics context we drew onto
UIImage *coloredImg = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

//return the colored image
[self setImage:coloredImg forState:controlState];

但是图像粗糙的边缘出现了。我尝试过使用屏幕,变亮和plusLighter混合模式,因为有些图像有白色部分,我想保持白色。我想要着色的唯一部分是黑色区域。我已经附加了原始按钮图像,并在它们被着色后。我不能让边缘看起来很好。当我将它们作为使用多重混合模式着色的白色图像时,它看起来好多了。但我想使用黑色,所以我可以使用一种方法来着色带有和不带白色的图像。我试过抗锯齿,这也没有帮助。看起来它不是抗锯齿它。我没有和Core Graphics合作过,知道它有什么用。

修改 这是原始PNG的样子: original image

以及它应该是什么样子: should look like

这就是它的样子: does look like

尺寸如果不同,但你可以看到边缘质量差。

2 个答案:

答案 0 :(得分:0)

也许你的原始图标(PNG?)只是“过于尖锐”?你能给我们看看吗?您只需将图像绘制为原始大小而不调整大小,因此问题可能从一开始就是正确的。

答案 1 :(得分:-1)

我不确定你在这里想要完成的是什么。你想要绕过图像的边缘吗?如果是这样,您最好通过更改UIButton图层的圆角属性。由于UIButton是UIView的子类,因此您可以获取其图层属性并更改边缘颜色并围绕其角落。

相关问题