quartz-graphics - 有没有办法将 CGContextDrawRadialGradient 绘制为椭圆形而不是完美的圆形?

标签 quartz-graphics gradient ellipse radial-gradients

我需要一个椭圆形或椭圆形的径向渐变,似乎 CGContextDrawRadialGradient 只能绘制一个完美的圆形。我一直在绘制方形上下文,然后复制/绘制到矩形上下文中。

有没有更好的方法来做到这一点?

谢谢!

最佳答案

我发现这样做的唯一方法是按照 Mark F 的建议,但我认为答案需要一个例子来更容易理解。

在 iOS 的 View 中绘制椭圆渐变(并使用 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);
}

放入一个黑色背景的 View ,你会得到:

enter image description here

关于quartz-graphics - 有没有办法将 CGContextDrawRadialGradient 绘制为椭圆形而不是完美的圆形?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6913208/

相关文章:

iphone - 有没有办法控制 iPhone 中 Quartz 绘制的多行文本的行高?

html - 渐变和圆 Angular CSS 的 IE9 显示问题

r - 如何将数据椭圆叠加在 ggplot2 散点图上?

R:绘制一个 95% 置信度椭圆并排除椭圆外的所有观测值

java - 在 JavaFX 中分组对象?

ios - Quartz Performance 绘图大缓冲区

iphone - 我想用 Quartz 将单色图像变成不同的颜色

android - 如何动画渐变?

swift - 渐变背景后UI消失