Drawing a simple linear gradient inside a rect that is inside a view
I'm reading the documentation about gradients and I'm a little bit lost. I have a view, and inside that view, I just want to draw a simple black to gray linear gradient inside a rect (smaller than the view), from bottom to top. How may I do that without subclassing anything (I've read many things that need to subclass the view)?
I'm searching a way to do this as simple as I've ever done on various platforms. Something like (language free :-) ) :
blackcolor = MakeBlack();
whiteColor = MakeWhite();
startPoint = MakeStartPoint();
endPoint = MakeEndPoint();
onthi开发者_StackOverflowsgraphicport = SetGraphicPort(self.view);
clippingRect = MakeClipRect();
DrawGradient(from:whiteColor, to:blackcolor, from:startPoint, to:endPoint, onthisgraphicport, intoThisRect:clippingRect);
Thank you for your help.
This code snippet might help. I found the code some time ago on the web. Unfortunately, I forgot the site, so not sure whom to give credit.
The code as is draws a white to black gradient. Just change the rect and the colors to your needs.
@interface MyView : UIView {
CGGradientRef _gradientRef;
}
@end
@implementation MyView
- (void) dealloc
{
[super dealloc];
}
- (id) initWithFrame:(CGRect)frame {
if ((self = [super initWithFrame:frame])) {
CGColorSpaceRef rgb = CGColorSpaceCreateDeviceRGB();
CGFloat colors[] =
{
1.0f, 1.0f, 1.0f, 1.0f,
0.0f, 0.0f, 0.0f, 1.0f,
};
_gradientRef = CGGradientCreateWithColorComponents(rgb, colors, NULL, sizeof(colors) / (sizeof(colors[0]) * 4));
CGColorSpaceRelease(rgb);
}
return self;
}
- (void) drawRect:(CGRect)rect {
CGContextRef context = UIGraphicsGetCurrentContext();
CGPoint start = rect.origin;
start.y = 0;
CGPoint end = CGPointMake(rect.origin.x, rect.size.height);
CGContextDrawLinearGradient(context, _gradientRef, start, end, kCGGradientDrawsBeforeStartLocation | kCGGradientDrawsAfterEndLocation);
[super drawRect:rect];
}
@end
精彩评论