OGeek|极客世界-中国程序员成长平台

标题: iphone - 用渐变绘制图形线 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 08:30
标题: iphone - 用渐变绘制图形线

这里有很多关于渐变图形的问题,但我找不到适合我的情况的解决方案。如何正确绘制多条路径?我想要这样的东西 - Gradient effect for Line Graph in iPhone

我可以很好地绘制渐变,但我需要将图形线放在渐变上方。我为此创建了另一条路径,并在绘制渐变后稍后绘制它,但它没有出现。我不画原始路径,因为它是封闭路径,但我想打开画线描边路径。

// create the path
CGMutablePathRef path = CGPathCreateMutable();
CGPathMoveToPoint(path, NULL, 0.0+offset, self.frame.size.height-0.0);

CGMutablePathRef strokePath = CGPathCreateMutable();

NSArray *graphValues = [delegate getDataForGraph];

float mulitplX = (self.frame.size.width - offset) / (float) ([graphValues count]-1);

float lastx;

for (int i = 0; i < [graphValues count]; i++) {
    CGPoint val = [[graphValues objectAtIndex: i] CGPointValue];
    lastx=val.x;
    CGPathAddLineToPoint(path, NULL, (val.x*mulitplX)+offset, self.frame.size.height-val.y);

    if (!i) {
        CGPathAddLineToPoint(strokePath, NULL,(val.x*mulitplX)+offset, self.frame.size.height-val.y);
    } else {
        CGPathMoveToPoint(strokePath, NULL, (val.x*mulitplX)+offset, self.frame.size.height-val.y);
    }            
}

//close path for gradient
CGPathAddLineToPoint(path, NULL, lastx*mulitplX+offset, self.frame.size.height-0.0);
CGPathAddLineToPoint(path, NULL, 0.0+offset, self.frame.size.height-0.0);

// setup the gradient
CGFloat locations[2] = { 1.0, 0.0 };
CGFloat components[8] = {
    0.95, 0.30, 0.30, 0.0,  // Start color
    0.93, 0.94, 0.30, 1.0   // End color
};
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGGradientRef gradientFill = CGGradientCreateWithColorComponents (colorSpace, components, locations, 2);

// setup gradient points
CGRect pathRect = CGPathGetBoundingBox(path);
CGPoint myStartPoint, myEndPoint;
myStartPoint.x = CGRectGetMinX(pathRect);
myStartPoint.y = CGRectGetMinY(pathRect);
myEndPoint.x = CGRectGetMinX(pathRect);
myEndPoint.y = CGRectGetMaxY(pathRect);

// draw the gradient
CGContextAddPath(context, path);
CGContextSaveGState(context);
CGContextClip(context);
CGContextDrawLinearGradient (context, gradientFill, myStartPoint, myEndPoint, 0);
CGContextRestoreGState(context);

// draw the graph - problem here
CGContextBeginPath(context);
CGContextAddPath(context, strokePath);
[[UIColor whiteColor] setStroke];
CGContextSetLineWidth(context, 2.0);
CGContextStrokePath(context);

// cleanup
CGColorSpaceRelease(colorSpace);
CGGradientRelease(gradientFill);
CGPathRelease(path);
CGPathRelease(strokePath);



Best Answer-推荐答案


有一个 WWDC 2011 session 由编写内置股票应用程序的人主持,其图表看起来与您正在尝试做的类似。他基本上花了整整一个小时来展示它是如何完成的。我忘记了确切的 session 标题,也许是核心动画?

关于iphone - 用渐变绘制图形线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6806927/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4