DrawRadialGradient绘制为椭圆形而不是完美的圆形

DrawRadialGradient绘制为椭圆形而不是完美的圆形

本文介绍了有没有一种方法可以将CGContextDrawRadialGradient绘制为椭圆形而不是完美的圆形?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个椭圆形或椭圆形的径向渐变,并且看起来CGContextDrawRadialGradient只能绘制一个完美的圆.我一直在绘制到方形上下文,然后将其复制/绘制到矩形上下文中.

I need a radial gradient in the shape of an oval or ellipse and it seems like it CGContextDrawRadialGradient can only draw a perfect circle. I've been drawing to a square context then copying/drawing into a rectangular context.

有更好的方法吗?

谢谢!

推荐答案

我发现这样做的唯一方法是Mark F所建议的,但是我认为答案需要一个例子以便于理解.

The only way I've found to do this is as Mark F suggested, but I think the answer needs an example to be easier to understand.

在iOS(和使用ARC)的视图中绘制椭圆渐变:

Draw an elliptical gradient in a view in iOS (and using 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);
}

在具有黑色背景的视图中输入:

Put in a view with a black background you get:

这篇关于有没有一种方法可以将CGContextDrawRadialGradient绘制为椭圆形而不是完美的圆形?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 09:33