CAShapeLayer笔画颜色不读取十六进制颜色代码转换

时间:2015-07-12 20:06:23

标签: ios uipickerview uicolor cashapelayer

我正在使用UIPickerView,它从具有十六进制颜色代码列表的数组中读取,然后使用这些代码用所有不同的颜色填充选择器视图的每一行。我正在使用一种方法将十六进制代码转换为RGB代码,并使用UIlabel来更改每一行的颜色。我的for循环改变了UIPickerView每行中的UILabel颜色工作得很好,但当我尝试使用相同的十六进制代码转换执行相同的颜色更改时,我在视图中使用CAShapeLayer绘制圆形的笔触颜色, 什么都没发生 。似乎UIColor不接受十六进制代码转换,尽管UILabel的背景是UIPickerView中的每一行。任何人都知道为什么这不起作用?

这是for循环,用于更改UIPicker视图中每行的UILabel背景颜色:

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{

UILabel *pickerLabel = [[UILabel alloc]init];

for (int currentIndex=0; currentIndex<[self.colorArray count]; currentIndex++) {

    [pickerLabel setBackgroundColor: [self colorWithHexString:[self.colorArray objectAtIndex:row]]];

}

return pickerLabel;
}

这是UIPickerView委托方法,我正在尝试更改我正在使用的CAShapeLayer的笔触颜色:

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row   inComponent:(NSInteger)component{

NSString *rowColorHex = [self.colorArray objectAtIndex:[self.picker selectedRowInComponent:0]];

[self.circleLayer setStrokeColor: [self colorWithHexString: rowColorHex];

//NSLog(@"%@", rowColorHex);
}

以下是我创建圆形的方法。请注意,我省略了初始笔触颜色。我可以在我的问题所在的UIPickerView的委托方法中以相同的方式指定笔触颜色,并且它可以正常工作:

CAShapeLayer *circleLayer = [CAShapeLayer layer];
circleLayer.lineWidth = 50;
circleLayer.fillColor = [[UIColor clearColor] CGColor];
//circleLayer.strokeColor = [[UIColor redColor] CGColor];
[self.imageToBeCropped.layer addSublayer:circleLayer];
self.circleLayer = circleLayer;

最后,这是十六进制转换方法:

-(UIColor*)colorWithHexString:(NSString*)hex{
NSString *cString = [[hex stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];

// String should be 6 or 8 characters
if ([cString length] < 6) return [UIColor grayColor];

// strip 0X if it appears
if ([cString hasPrefix:@"0X"]) cString = [cString substringFromIndex:2];

if ([cString length] != 6) return  [UIColor grayColor];

// Separate into r, g, b substrings
NSRange range;
range.location = 0;
range.length = 2;
NSString *rString = [cString substringWithRange:range];

range.location = 2;
NSString *gString = [cString substringWithRange:range];

range.location = 4;
NSString *bString = [cString substringWithRange:range];

// Scan values
unsigned int r, g, b;
[[NSScanner scannerWithString:rString] scanHexInt:&r];
[[NSScanner scannerWithString:gString] scanHexInt:&g];
[[NSScanner scannerWithString:bString] scanHexInt:&b];

return [UIColor colorWithRed:((float) r / 255.0f)
                       green:((float) g / 255.0f)
                        blue:((float) b / 255.0f)
                       alpha:1.0f];
}

1 个答案:

答案 0 :(得分:1)

Core Animation图层不接受UIKit类型 - 您需要使用Core Graphics等效项,在本例中为CGColorRef。您已经在已创建它的代码中执行此操作,但您的-colorWithHexString:方法会返回UIColor

[self.circleLayer setStrokeColor:[[self colorWithHexString: rowColorHex] CGColor]];