问题描述
- 从UISlider获取RGB颜色
-
改变UISLider的值使用方法:@property (strong, nonatomic) IBOutlet UISlider *r; @property (strong, nonatomic) IBOutlet UISlider *g; @property (strong, nonatomic) IBOutlet UISlider *b; @property (strong, nonatomic) IBOutlet UILabel *colorLabel; - (void)viewDidLoad { [super viewDidLoad]; _r.minimumValue=0; _r.maximumValue=255; _g.minimumValue=0; _g.maximumValue=255; _b.minimumValue=0; _b.maximumValue=255; // Do any additional setup after loading the view, typically from a nib. } -(void)sliderValueChanged:(UISlider*)slider { [_colorLabel setBackgroundColor:[UIColor colorWithRed:_r.value green:_g.value blue:_b.value alpha:1]]; }
谢谢~
解决方案
设置颜色方法:
-(void)sliderValueChanged:(UISlider*)slider
{
float r=[[NSString stringWithFormat:@"%.0f",_r.value] floatValue];
float g=[[NSString stringWithFormat:@"%.0f",_g.value]floatValue];
float b=[[NSString stringWithFormat:@"%.0f",_b.value]floatValue];
UIColor *colorToSet=[UIColor colorWithRed:(r/255.0f) green:(g/255.0f) blue:(b/255.0f) alpha:1];
[_colorLabel setBackgroundColor:colorToSet];
}
解决方案二:
你这个问题的关键在于:你在拿到UISlider的value后,使用[UIColor colorWithRed:green:blue:alpha:] 时并没有将得到各颜色的值除以255.0
UIColor *bgColor=[UIColor colorWithRed:_r.value/255.0f green:_g.value/255.0f blue:_b.value/255.0f alpha:1];
[_colorLabel setBackgroundColor:colorToSet];
时间: 2024-11-02 17:22:21