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];

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

編集 元のPNGは次のようになります。 元の画像

これは次のようになります。 のように見えるはずです

そして、これは次のようになります。 のように見える

サイズは異なりますが、エッジの周りに品質の悪さが見られます。

4

2 に答える 2

0

元のアイコン (PNG?) が「シャープすぎる」だけではないでしょうか? 見せていただけますか?サイズを変更せずに元のサイズで画像を描画するだけなので、最初から問題が発生する可能性があります。

于 2012-08-08T20:54:31.353 に答える
-1

ここで何を達成しようとしているのかわかりません。画像の端を丸くしようとしていますか?その場合は、UIButton のレイヤーの角を丸くするプロパティを変更することをお勧めします。UIButton は UIView のサブクラスであるため、レイヤー プロパティを取得し、エッジの色を変更したり、角を丸めたりすることができます。

于 2012-08-08T20:52:46.487 に答える