绘制渐变方向

时间:2012-06-05 19:32:56

标签: iphone objective-c ipad core-graphics

所以我有以下代码:

-

 (void) drawLinearGradient:(CGRect) rect
{
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGFloat locations[] = { 0.0, 0.3, 1.0 };

    CGColorRef grayColor = [UIColor colorWithRed:37/255.f green:37/255.f 
                                            blue:37/255.f alpha:1.0].CGColor; 
    CGColorRef blueColor = [UIColor colorWithRed:23.0/255.0 green:171.0/255.0 
                                            blue:219.0/255.0 alpha:1.0].CGColor;

    NSArray *colors = [NSArray arrayWithObjects: (id) grayColor, (id) grayColor, (id) blueColor, nil];

    CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, 
                                                        (CFArrayRef) colors, locations);

    CGPoint startPoint = CGPointMake(CGRectGetMidX(rect), CGRectGetMinY(rect));
    CGPoint endPoint = CGPointMake(CGRectGetMidX(rect), CGRectGetMaxY(rect));

    CGContextSaveGState(context);
    CGContextAddRect(context, rect);
    CGContextClip(context);
    CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, 0);
    CGContextRestoreGState(context);

    CGGradientRelease(gradient);
    CGColorSpaceRelease(colorSpace);
}

这样做是从上到下绘制渐变,我怎样才能使它从左到右绘制?

1 个答案:

答案 0 :(得分:6)

更改这两行:

CGPoint startPoint = CGPointMake(CGRectGetMidX(rect), CGRectGetMinY(rect));
CGPoint endPoint = CGPointMake(CGRectGetMidX(rect), CGRectGetMaxY(rect));

为:

CGPoint startPoint = CGPointMake(CGRectGetMinX(rect), CGRectGetMidY(rect));
CGPoint endPoint = CGPointMake(CGRectGetMaxX(rect), CGRectGetMidY(rect));