Wednesday, July 27, 2011

How to draw 2D doughnut shape using QuartzCore?

You want to create a 2D figure which looks like doughnut. Use following code:




- (void)drawRect:(CGRect)rect
{
    
    float _outerRadius=350.0;
    float _innerRadius=248.0
    
    
    // Create the context
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    //Make sure the remove the anti-alias effect from circle
    CGContextSetAllowsAntialiasing(context, true);
    CGContextSetShouldAntialias(context, true);
    
    
    
    
    //orange
    float dRed=0.9f;
    float dGreen=0.38f;
    float dBlue=0.0f;
    
    float lRed=1.0f;
    float lGreen=0.61f;
    float lBlue=0.0f;
    
    
    CGContextAddArc(context, _outerRadius/2, _outerRadius/2, _outerRadius/2, 0, 360, 0);
    CGContextClip(context);
    
    //Create the gradient
    CGGradientRef glossGradient;
    CGColorSpaceRef rgbColorspace;
    size_t num_locations = 2;
    CGFloat locations[2] = { 0.0, 1.0 };
    CGFloat components[8] = { lRed, lGreen, lBlue, 0.9 ,   // Start color
        dRed, dGreen, dBlue, 0.9}; // Mid color and End color
    rgbColorspace = CGColorSpaceCreateDeviceRGB();
    glossGradient = CGGradientCreateWithColorComponents(rgbColorspace, components, locations, num_locations);
    
    //Draw the gradient
    CGPoint start = CGPointMake(0,self.center.y); 
    CGPoint end = CGPointMake(_outerRadius,self.center.y);
    CGContextDrawLinearGradient(context, glossGradient, start, end, kCGGradientDrawsBeforeStartLocation);
    
    //Draw the hole to make it look like doughnut
    CGContextSetFillColorWithColor( context, [UIColor whiteColor].CGColor );
    CGContextSetBlendMode(context, kCGBlendModeClear);
    CGRect holeRect= CGRectMake((_outerRadius-_innerRadius-2)/2, (_outerRadius-_innerRadius-2)/2, _innerRadius+1, _innerRadius+1);
    CGContextFillEllipseInRect( context, holeRect );
    
    
}





This code will make a doughnut as shown in following screenshot. (Please ignore the check texture in the background of screenshot, that will not be generated with above code, Only orange doughnut will be generated). You can use your own created gradient by changing the values in gradient.




No comments:

Post a Comment