このコードを使用して、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];
しかし、画像は粗いエッジで出てきます。一部の画像には白のままにしたい白い部分があるため、screen、lighten、およびplusLighterブレンドモードを使用してみました。色付けしたいのは黒い部分だけです。元のボタン画像を添付し、色付けした後. エッジがきれいに見えません。乗算ブレンドモードを使用して色付けされた白い画像としてそれらを持っていたとき、それはずっと良く見えました. しかし、私は黒を使いたいので、白の有無にかかわらず画像を色付けするための 1 つの方法を使用できます。アンチエイリアシングを試しましたが、それも役に立ちませんでした。アンチエイリアスがかかっていないようです。私は Core Graphics で何が起こっているのかを知るのに十分なほど働いていません。
編集
元のPNGは次のようになります。
これは次のようになります。
そして、これは次のようになります。
サイズは異なりますが、エッジの周りに品質の悪さが見られます。