【发布时间】:2017-02-04 02:11:29
【问题描述】:
我正在尝试将角度渐变应用于使用我在自定义 UIView 类中编写的代码创建的破折号,如下所示。虽然它需要调整,但我对它迄今为止产生的结果感到满意。
给定视图初始化中的输入参数(如下),以及 iPad Air2 纵向模式下的 768 * 768 帧,它会生成以下仪表:
我想做的是使每个破折号逐步通过用户定义的渐变,例如从绿色到红色,很像这样(在 Photoshop 中拼凑):
我搜索了高低,找不到任何东西来实现这一点。唯一接近的东西使用不同的绘图方法,我想保持我的绘图程序。
就我而言,我应该能够调用:
CGContextSetStrokeColorWithColor(myContext, [这里是渐变色])
在绘图循环中,就是这样,但我不知道如何创建相关的颜色数组/渐变,并根据该数组的索引更改线条绘制颜色。
任何帮助将不胜感激。
- (void)drawRect:(CGRect)rect {
myContext = UIGraphicsGetCurrentContext();
UIImage *gaugeImage = [self radials:300 andSteps:3 andLineWidth:10.0];
UIImageView *gaugeImageView = [[UIImageView alloc] initWithImage:gaugeImage];
[self addSubview:gaugeImageView];
}
-(UIImage *)radials:(NSInteger)degrees andSteps:(NSInteger)steps andLineWidth:(CGFloat)lineWidth{
UIGraphicsBeginImageContext(self.bounds.size);
myContext = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(myContext, lineWidth);
CGContextSetStrokeColorWithColor(myContext, [[UIColor blackColor] CGColor]);
CGPoint center = CGPointMake(self.bounds.origin.x+(self.bounds.size.width/2), self.bounds.origin.y+(self.bounds.size.height/2));
CGFloat r1 = center.x * 0.87f;
CGFloat r2 = center.x * 0.95f;
CGContextTranslateCTM(myContext, center.x, center.y);
CGContextBeginPath(myContext);
CGFloat offset = 0;
if(degrees < 360){
offset = (360-degrees) / 2;
}
for(int lp = offset + 0 ; lp < offset + degrees+1 ; lp+=steps){
CGFloat theta = lp * (2 * M_PI / 360);
CGContextMoveToPoint(myContext, 0, 0);
r1 = center.x * 0.87f;
if(lp % 10 == 0){
r1 = center.x * 0.81f;
}
CGContextMoveToPoint(myContext, sin(theta) * r1, cos(theta) * r1);
CGContextAddLineToPoint(myContext, sin(theta) * r2, cos(theta) * r2);
CGContextStrokePath(myContext);
}
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
【问题讨论】:
-
不要这样滥用
drawRect。drawRect用于绘图——而不是用于添加子视图。请记住,drawRect被多次调用,而您只是一次又一次地添加该子视图,这太荒谬了。 -
点了!我的错!
标签: ios core-graphics gradient angle gauge