Quartz2D和渐变线

时间:2010-04-19 05:28:23

标签: iphone objective-c xcode macos quartz-graphics

如何用quartz2d绘制渐变线?

2 个答案:

答案 0 :(得分:3)

CGContextDrawLinearGradient绘制渐变。使用CGContextClipToRect(或相关裁剪功能)剪切到要用渐变填充的区域。

不支持使用渐变来抚摸或填充路径,而是剪切到要填充的区域。

答案 1 :(得分:1)

我在drawRect:内使用了这个,并且像魅力一样:

double slope, cosy, siny;
double halfWidth = 2; // the thickness of the line will be 2*halfWith

// the start and end points have to be inside UIView frame coordinates
CGPoint start = CGPointMake(30, 20);
CGPoint end = CGPointMake(80, 90);  

slope = atan2((start.y - end.y), (start.x - end.x));
cosy = cos(slope);
siny = sin(slope);

CGContextRef context = UIGraphicsGetCurrentContext();

CGGradientRef myGradient;
CGColorSpaceRef myColorspace;
size_t num_locations = 2;
CGFloat locations[2] = { 0.0, 1.0 };
CGFloat components[8] = { 1.0, 1.0, 1.0, 1.0,  // Start color (White)
                          1.0, 0.0, 0.0, 1.0 }; // End color (Red)

myColorspace = CGColorSpaceCreateDeviceRGB();
myGradient = CGGradientCreateWithColorComponents (myColorspace, components, locations, num_locations);

CGContextMoveToPoint(context, start.x -halfWidth*siny , start.y +halfWidth*cosy);
CGContextAddLineToPoint(context, end.x -halfWidth*siny , end.y +halfWidth*cosy  );
CGContextAddLineToPoint(context, end.x +halfWidth*siny , end.y -halfWidth*cosy );
CGContextAddLineToPoint(context, start.x +halfWidth*siny, start.y -halfWidth*cosy);
CGContextAddLineToPoint(context, start.x -halfWidth*siny , start.y +halfWidth*cosy);    
CGContextClip(context);

CGContextDrawLinearGradient (context, myGradient, start, end, 0);
CGColorSpaceRelease( myColorspace );
CGGradientRelease (myGradient);
相关问题