2012-08-08 224 views
2

我使用这个代码上色一个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

大小如果不同,但您可以看到边缘周围的质量差。

+0

你可以发布一个你想要它看起来像什么和它看起来像什么样子的样机吗? – 2012-08-08 20:54:16

+0

我认为这个问题与图像外部的灰度像素来自抗锯齿有关。不知道如何解决,虽然 – Marty 2012-08-08 21:43:28

回答

0

也许你的原始图标(PNGs?)只是“太尖锐”?你能告诉我们吗?您只需以原始大小绘制图像而不调整大小,因此问题可能从一开始就是正确的。

+0

我添加了一些图像到我的问题 – Marty 2012-08-08 21:19:56

-1

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