【发布时间】:2011-06-15 13:16:46
【问题描述】:
我一直在用头撞墙很长时间试图弄清楚为什么这不起作用。
基本上,我正在尝试使用 CGPath 绘制图形(图表),然后使用它来剪辑渐变。最终效果应该像 iPhone 自带的 Stocks 应用。
渐变和路径分别绘制为两个分层(未剪辑)的元素。但是如果我注释掉 CGContextDrawPath,线条和渐变都不会绘制到屏幕上。
这是我的 drawRect 代码:
CGContextRef context = UIGraphicsGetCurrentContext();
[[UIColor whiteColor] set];
CGContextSetLineWidth(context, 2.0f);
CGPoint lastDrawnPt = [[points objectAtIndex:0] CGPointValue];
CGPoint firstDrawnPt = lastDrawnPt;
//create the path for the gradient
CGMutablePathRef thePath = CGPathCreateMutable();
CGPathMoveToPoint(thePath, NULL, lastDrawnPt.x, self.bounds.size.height); // bottom left
CGPathAddLineToPoint(thePath, NULL, lastDrawnPt.x, lastDrawnPt.y);
for (int i=0; i<(points.count-1); i++) {
//CGPoint pt1 = [[points objectAtIndex:i] CGPointValue];
CGPoint pt2 = [[points objectAtIndex:i+1] CGPointValue];
if (pt2.x > lastDrawnPt.x+2) {
// only draw if we've moved sunstantially to the right
//for the gradient
CGPathMoveToPoint(thePath, NULL, lastDrawnPt.x, lastDrawnPt.y);
CGPathAddLineToPoint(thePath, NULL, pt2.x, pt2.y);
lastDrawnPt = pt2;
}
}
//finish the gradient clipping path
CGPathMoveToPoint(thePath, NULL, lastDrawnPt.x, lastDrawnPt.y);
CGPathAddLineToPoint(thePath, NULL, lastDrawnPt.x, self.bounds.size.height); // bottom right
CGPathMoveToPoint(thePath, NULL, lastDrawnPt.x, self.bounds.size.height);
CGPathAddLineToPoint(thePath, NULL, firstDrawnPt.x, self.bounds.size.height); // bottom right
CGPathCloseSubpath(thePath);
//add the gradient clipping path to the context
CGContextSaveGState(context);
CGContextAddPath(context, thePath);
//draw the path
float components[4] = {1.0, 1.0, 1.0, 1.0};
CGContextSetStrokeColor(context, components);
CGContextDrawPath(context,kCGPathStroke);
//clip the path
CGContextClip(context);
//Draw Gradient
UIColor *topColor = [UIColor colorWithRed: 1.0 green:1.0 blue:1.0 alpha:1.0];
UIColor *bottomColor = [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:0.0];
CGColorRef colorRef[] = { [topColor CGColor], [bottomColor CGColor] };
CFArrayRef colors = CFArrayCreate(NULL, (const void**)colorRef, sizeof(colorRef) / sizeof(CGColorRef), &kCFTypeArrayCallBacks);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, colors, NULL);
CFRelease(colorSpace);
CFRelease(colors);
// Draw a linear gradient from top to bottom
CGPoint gradStartPoint = CGPointMake(50.0, self.bounds.size.height);
CGPoint gradEndPoint = CGPointMake(50.0, 0.0);
CGContextDrawLinearGradient(context, gradient, gradStartPoint, gradEndPoint, 0);
CFRelease(gradient);
// Cleanup
CGColorSpaceRelease(colorSpace);
CGContextRestoreGState(context);
【问题讨论】:
-
您是否尝试过 CGContextFlush 或 CGContextSynchronize... 我认为这可能与分层有关。还可以尝试在绘制渐变后移动 CGContextClip...
-
感谢您的建议,但它们似乎没有帮助。
-
我开始认为我构建路径的方式有问题。
-
当我将绘图路径线更改为 CGContextDrawPath(context,kCGPathFillStroke);它根本没有填满路径......这是一个线索吗?
-
你能举例说明点数组包含什么吗?
标签: iphone cocoa-touch core-graphics quartz-2d