1

私はCAGradientLayer自分のイメージで使用しています。これを行うには、次のコードを使用します。

UIImage *image = [UIImage imageNamed:@"perfect.jpg"];

[testImage setImage:image];

CAGradientLayer *myLayer = [CAGradientLayer layer];

myLayer.anchorPoint = CGPointZero;

//starts in bottom left
myLayer.startPoint = CGPointMake(1.0f,1.0f);

//ends in top right
myLayer.endPoint = CGPointMake(1.0f, 0.0f);

UIColor *outerColor = [UIColor colorWithWhite:1.0 alpha:0.0];
UIColor *innerColor = [UIColor colorWithWhite:1.0 alpha:1.0];

//an array of colors that dictatates the gradient(s)
myLayer.colors = @[(id)outerColor.CGColor, (id)outerColor.CGColor, (id)innerColor.CGColor, (id)innerColor.CGColor];

//these are percentage points along the line defined by our startPoint and endPoint and correspond to our colors array. The gradient will shift between the colors between these percentage points.
myLayer.locations = @[@0.0, @0.15, @0.5, @1.0f];

myLayer.bounds = CGRectMake(0, 0, CGRectGetWidth(testImage.bounds), CGRectGetHeight(testImage.bounds));

testImage.layer.mask = myLayer;

[self.view addSubview:testImage];

しかし、私が欲しいのは、放射状グラデーションまたは円形グラデーション効果です。片側だけグラデーションがかかっています。円形のグラデーション レイヤーを作成するにはどうすればよいですか? ありがとう。

4

2 に答える 2

0

円形のグラデーション レイヤーが必要な場合は、- (void)drawInContext:(CGContextRef)ctxメソッドをサブクラス化してオーバーライドする必要があります。コードは非常に単純で、放射状グラデーションの場合は次のようになります。

        CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
        NSArray* colors = @[(id)[UIColor whiteColor].CGColor, (id)[UIColor blackColor].CGColor];
        CGFloat locations[] = {.25, .75};
        CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (CFArrayRef)colors, locations);
        CGPoint center = (CGPoint){self.bounds.size.width / 2, self.bounds.size.height  / 2};
        CGContextDrawRadialGradient(ctx, gradient, center, 20, center, 40, kCGGradientDrawsAfterEndLocation);

        CGGradientRelease(gradient);
        CGColorSpaceRelease(colorSpace);

現在コードをテストすることはできませんが、問題ないはずです。放射状グラデーションの代わりに、次のような角度グラデーションが必要な場合:

ここに画像の説明を入力

Objective c には直接作成する方法がないため、不運です。それを行うには、必要な色の間の線形補間をループして直接描画するか (実装はそれほど難しくありませんが、パフォーマンスは低下します)、画像をマスクとして使用できます。

于 2014-05-06T07:11:57.457 に答える