【发布时间】:2015-07-12 20:06:23
【问题描述】:
我正在使用一个 UIPickerView,它从一个包含十六进制颜色代码列表的数组中读取数据,然后用这些颜色代码填充选取器视图的每一行所有不同的颜色。我正在使用一种将十六进制代码转换为 RGB 代码的方法,以及一个 UIlabel 来更改每一行的颜色。我的用于更改 UIPickerView 每一行中的 UILabel 颜色的 for 循环工作得很好,但是当我尝试使用相同的十六进制代码转换执行相同的颜色更改时,我正在使用 CAShapeLayer 在视图中绘制圆的笔触颜色, 没发生什么事 。似乎 UIColor 不接受十六进制代码转换,尽管 UIPickerView 中每一行的 UILabel 的背景都可以。任何人都知道为什么这不起作用?
这是改变 UIPickerView 中每一行的 UILabel 背景颜色的 for 循环:
- (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;
}
这是我尝试更改正在使用的 CAShapeLayer 的笔触颜色的 UIPickerView 委托方法:
- (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];
}
【问题讨论】:
-
您能否附上您的
UIPickerView当前渲染方式的屏幕截图?
标签: ios uipickerview uicolor cashapelayer