Thursday, March 22, 2012

Adding more than 1 item filled with gradient to your UIView ?

In previous article,   we talked about how to fill gradient in a clipped area on your screen. What if you have more than 1 shape to be displayed on your screen. As mentioned previously you need to use CGContextSaveGState(context) and CGContextRestoreGState(context).


Lets add these 2 commands to our code where we created and arc with gradient filled.


   //Add Arc with gradient
   CGContextSaveGState(context);
   CGContextMoveToPoint(context, 100, 100);
   CGContextAddArc(context, 100, 100, radius, 1.04 , 2.09 , 0);
   CGContextClosePath(context);
   CGContextClip(context);


   CGPoint endshine;
   CGPoint startshine;
   startshine = CGPointMake(100 + radius * cosf( 1.57 ),100+ radius * sinf( 1.57 ));
   endshine = CGPointMake(100,100);
   CGContextDrawLinearGradient(context,gradient , startshine, endshine, kCGGradientDrawsAfterEndLocation);
   CGContextRestoreGState(context);




Lets add a square with gradient. Of course you can change the gradient of your own colors of choice. But for now let it have same gradient colors.Make sure to keep the code bound in CGContextSaveGState(context) and CGContextRestoreGState(context) , so that we can keep adding more shapes to our scene without getting it clipped.

   //Add Square WITH GRADIENT
   CGContextSaveGState(context);
   CGContextAddRect(context, CGRectMake(5, 5, 50, 50));
   CGContextClip(context);

   startshine = CGPointMake(5,55);
   endshine = CGPointMake(5,5);
   CGContextDrawLinearGradient(context,gradient , startshine, endshine, kCGGradientDrawsAfterEndLocation);
   CGContextRestoreGState(context);




Now lets add finally a circle which has same gradient colors to our scene.

   //Add Circle WITH GRADIENT
   CGContextSaveGState(context);
   CGContextAddEllipseInRect(context, CGRectMake(105, 5, 70, 70));
   CGContextClip(context);

   CGPoint startPoint = CGPointMake(140, 40);
   CGPoint endPoint = CGPointMake(140, 40);
   CGContextDrawRadialGradient(context, gradient, startPoint, 5,endPoint , 35, kCGGradientDrawsBeforeStartLocation);
   CGContextRestoreGState(context);




Now on running the code, our scene will look like following:




No comments:

Post a Comment