如何使用Core Graphics / iPhone绘制渐变线(淡入/淡出)? [英] How to draw a gradient line (fading in/out) with Core Graphics/iPhone?

查看:197
本文介绍了如何使用Core Graphics / iPhone绘制渐变线(淡入/淡出)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如何绘制一条简单的行:

I know how to draw a simple line:

CGContextSetRGBStrokeColor(context, 1.0, 1.0, 1.0, 1.0);
CGContextMoveToPoint(context, x, y);
CGContextAddLineToPoint(context, x2, y2);
CGContextStrokePath(context);

我知道如何做一个渐变矩形,ig:

And I know how to do a gradient rectangle, i.g.:

CGColorSpaceRef myColorspace=CGColorSpaceCreateDeviceRGB();
size_t num_locations = 2;
CGFloat locations[2] = { 1.0, 0.0 };
CGFloat components[8] = { 0.0, 0.0, 0.0, 1.0,    1.0, 1.0, 1.0, 1.0 };

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

CGPoint myStartPoint, myEndPoint;
myStartPoint.x = 0.0;
myStartPoint.y = 0.0;
myEndPoint.x = 0.0;
myEndPoint.y = 10.0;
CGContextDrawLinearGradient (context, myGradient, myStartPoint, myEndPoint, 0);

但我怎么能用渐变画一条线,例如。从黑色渐变到白色(也可能在另一边淡出黑色)?

But how could I draw a line with a gradient, i.g. fading in from black to white (and maybe fading out to black on the other side as well) ?

推荐答案

经过多次尝试我我现在确定渐变不会影响笔画,所以我认为用 CGContextStrokePath()绘制渐变线是不可能的。对于水平和垂直线,解决方案是使用 CGContextAddRect(),幸运的是我需要的。我替换了

After several tries I'm now sure that gradients doesn't affect strokes, so I think it's impossible to draw gradient lines with CGContextStrokePath(). For horizontal and vertical lines the solution is to use CGContextAddRect() instead, which fortunately is what I need. I replaced

CGContextMoveToPoint(context, x, y);
CGContextAddLineToPoint(context, x2, y2);
CGContextStrokePath(context);

with

CGContextSaveGState(context);
CGContextAddRect(context, CGRectMake(x, y, width, height));
CGContextClip(context);
CGContextDrawLinearGradient (context, gradient, startPoint, endPoint, 0);
CGContextRestoreGState(context);

一切正常。感谢Brad Larson的关键提示。

and everything works fine. Thanks to Brad Larson for the crucial hint.

这篇关于如何使用Core Graphics / iPhone绘制渐变线(淡入/淡出)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆