9

楕円形または楕円形の放射状グラデーションが必要ですが、CGContextDrawRadialGradient は完全な円しか描画できないようです。私は正方形のコンテキストに描画してから、長方形のコンテキストにコピー/描画しています。

これを行うより良い方法はありますか?

ありがとう!

4

2 に答える 2

6

これを行う唯一の方法は、Mark F が提案したとおりですが、理解しやすいようにするには、例が必要だと思います。

iOS (および ARC を使用) のビューで楕円形のグラデーションを描画します。

- (void)drawRect:(CGRect)rect {

    CGContextRef ctx = UIGraphicsGetCurrentContext();

    // Create gradient
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGFloat locations[] = {0.0, 1.0};

    UIColor *centerColor = [UIColor orangeColor];
    UIColor *edgeColor = [UIColor purpleColor];

    NSArray *colors = [NSArray arrayWithObjects:(__bridge id)centerColor.CGColor, (__bridge id)edgeColor.CGColor, nil];
    CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (__bridge CFArrayRef)colors, locations);

    // Scaling transformation and keeping track of the inverse
    CGAffineTransform scaleT = CGAffineTransformMakeScale(2, 1.0);
    CGAffineTransform invScaleT = CGAffineTransformInvert(scaleT);

    // Extract the Sx and Sy elements from the inverse matrix
    // (See the Quartz documentation for the math behind the matrices)
    CGPoint invS = CGPointMake(invScaleT.a, invScaleT.d);

    // Transform center and radius of gradient with the inverse
    CGPoint center = CGPointMake((self.bounds.size.width / 2) * invS.x, (self.bounds.size.height / 2) * invS.y);
    CGFloat radius = (self.bounds.size.width / 2) * invS.x;

    // Draw the gradient with the scale transform on the context
    CGContextScaleCTM(ctx, scaleT.a, scaleT.d);
    CGContextDrawRadialGradient(ctx, gradient, center, 0, center, radius, kCGGradientDrawsBeforeStartLocation);

    // Reset the context
    CGContextScaleCTM(ctx, invS.x, invS.y);

    // Continue to draw whatever else ...

    // Clean up the memory used by Quartz
    CGGradientRelease(gradient);
    CGColorSpaceRelease(colorSpace);
}

あなたが得る黒の背景を持つビューに入れます:

ここに画像の説明を入力

于 2012-09-30T21:12:46.137 に答える
4

楕円を描画するようにコンテキストの変換を変更できます (たとえば、CGContextDrawRadialGradient () を呼び出す直前に CGContextScaleCTM(context, 2.0, 1.0) を適用して、高さの 2 倍の幅の楕円グラデーションを描画します)。ただし、始点と終点に逆変換を適用することを忘れないでください。

于 2012-01-09T05:27:22.977 に答える