9

フラグに応じてカラーまたは白黒で描画できるUIImageViewが必要です。

  BOOL isGrey;

QuartzブレンドモードをColorに設定して、元の画像の上に黒い長方形を描画することでそれを実行しようとしています。これは、画像のアルファマスクを尊重しないことを除いて機能します。

図を参照してください: 代替テキストhttp://img214.imageshack.us/img214/1407/converttogreyscaleillo.png

グーグルとSOを検索して、私はいくつかの解決策を見つけて試しましたが、どれもマスクを尊重していません。

上記の「WhatIget」画像を生成するコードは次のとおりです。

 - (void)drawRect:(CGRect)rect {

    if (isGrey) {
        CGContextRef context = UIGraphicsGetCurrentContext();

        // flip orientation
        CGContextTranslateCTM(context, 0, self.bounds.size.height);
        CGContextScaleCTM(context, 1.0, -1.0);

        // draw the image
        CGContextDrawImage(context, self.bounds, self.image.CGImage);

        // set the blend mode and draw rectangle on top of image
        CGContextSetBlendMode(context, kCGBlendModeSaturation);
        CGContextSetRGBFillColor(context, 0.0, 0.0, 0.0, 1.0);
        CGContextFillRect(context, rect);       
    } else {
        [self.image drawInRect:rect];
    }
}

設定し忘れているクォーツ描画モードはありますか?Quartzプログラミングガイドを調べましたが、重複してハイパーリンクされている主題から必要な情報を1ビット抽出するのは非常に困難です。

明らかに、表示されている円だけでなく、マスクされた形状の画像に適用される一般的な解決策を探しています。

4

4 に答える 4

11

画像のアルファ マスクを尊重しながら図形を描画するには、描画する前に 1 行追加するだけです。

 CGContextClipToMask(context, self.bounds, image.CGImage);

 // example usage
  - (void)drawRect:(CGRect)rect {

    if (isGrey) {
            CGContextRef context = UIGraphicsGetCurrentContext();

            // flip orientation
            CGContextTranslateCTM(context, 0.0, self.bounds.size.height);
            CGContextScaleCTM(context, 1.0, -1.0);

            // draw the image
            CGContextDrawImage(context, self.bounds, self.image.CGImage);

            // set the blend mode and draw rectangle on top of image
            CGContextSetBlendMode(context, kCGBlendModeColor);
            CGContextClipToMask(context, self.bounds, image.CGImage); // respect alpha mask
            CGContextSetRGBFillColor(context, 0.0, 0.0, 0.0, 1.0);
            CGContextFillRect(context, rect);               
    } else {
            [self.image drawInRect:rect];
    }

}

于 2009-09-05T08:52:53.437 に答える
1

簡単な方法で、あなたが持っている丸い画像と同じサイズの黒い円を描きます。おそらくあなたが求めているものではありません。

于 2009-08-31T09:38:00.843 に答える
0

ビューの Core Animation レイヤーにマスクを追加してみてください。

CALayer *maskLayer = [CALayer layer];
[maskLayer setBounds:CGRectMake(0.0f, 0.0f, 100.0f, 100.0f)];

// Center the layer
[maskLayer setPosition:CGPointMake([self view].bounds.size.width/2, 
                          [self view].bounds.size.height/2)];

// Set the cornerRadius to half the width/height to get a circle.
[maskLayer setCornerRadius:50.f];
[maskLayer setMasksToBounds:YES];

// Any solid color will do. Just using black here.
[maskLayer setBackgroundColor:[[UIColor blackColor] CGColor]];

// Set the mask which will only allow that which is in the
// circle show through
[[[self view] layer] setMask:maskLayer];

もう1つの考え。画像の白黒バージョンを作成して、フラグに応じて交換できないのはなぜですか?

于 2009-08-28T16:39:14.723 に答える