开发者

iphone Drawing gradient inside a polygon

开发者 https://www.devze.com 2023-04-09 05:22 出处:网络
I want to draw a gradient inside a polygon using core graphics. I am able to draw a hexagon using the code below but i don\'t know how to fill this hexagon with a gradient color. Any help will be real

I want to draw a gradient inside a polygon using core graphics. I am able to draw a hexagon using the code below but i don't know how to fill this hexagon with a gradient color. Any help will be really appreciated.

- (void)drawRect:(CGRect)rect
 {
    // Drawing code.

    CGContextRef context = UIGraphicsGetCurrentContext(); 

    CGContextSetRGBStrokeColor(context, 1.0, 1.0, 1.0, 1.0);

    CGContextSetRGBFillColor(context, 0.0, 0.0, 1.0, 1.0);

    CGContextSetLineWidth(context, 2.0);

    CGPoint center;

    center = CGPointMake(210.0, 90.0);

    CGContextMoveToPoint(context, center.x, center.y + 60.0);

    for(int i = 1;开发者_如何学编程 i < 6; ++i)
    {   
          CGFloat x = 60.0 * sinf(i * 2.0 * M_PI / 6.0);

          CGFloat y = 60.0 * cosf(i * 2.0 * M_PI / 6.0);

          CGContextAddLineToPoint(context, center.x + x, center.y + y);
    }

    CGContextClosePath(context);
    CGContextDrawPath(context, kCGPathFillStroke);
}


Use following code for Gradient fill

CGContextRef context    = UIGraphicsGetCurrentContext();

CGColorSpaceRef rgb = CGColorSpaceCreateDeviceRGB();

CGFloat colors[] =

{


    0.62890625, 0.859375, 10.9921875, 1.00,
    0.65625, 0.8046875, 0.9453125, 1.00,
};

CGGradientRef gradient = CGGradientCreateWithColorComponents(rgb, colors, NULL, sizeof(colors)/(sizeof(colors[0])*4));

CGColorSpaceRelease(rgb);



// now we can actually create the shape and fill it



CGPoint start, end;



CGContextSetRGBFillColor(context, 0, 0, 0.6, 0.1);

CGContextFillEllipseInRect(context, CGRectMake(0.0, 0.0, 100.0, 100.0));

CGContextStrokeEllipseInRect(context, CGRectMake(0.0, 0.0, 100.0, 100.0));



// Gradient

CGRect myrect = CGRectMake(0.0, 0.0, rect.size.width, rect.size.height);

CGContextSaveGState(context);

CGContextClipToRect(context, myrect);

start = CGPointMake(myrect.origin.x, myrect.origin.y + myrect.size.height * 0.25);

end = CGPointMake(myrect.origin.x, myrect.origin.y + myrect.size.height * 1.0);

CGContextDrawLinearGradient(context, gradient, start, end, kCGGradientDrawsBeforeStartLocation);

CGContextRestoreGState(context);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号