我想为选定的单元格和背景单元格生成相同的随机颜色。我用流动的代码成功实现了它。但有了这个我正确得到cell.background颜色,但我想在所选单元格的每个索引路径上设置浅色。那么,我该怎么办呢? 假设,
if (indexpath.row ==1) {
// lightcolor
}
if (indexpath.row == 2) {
// More light color as compare to indexpath.row ==1
}
@interface DisplayViewController () {
DisplayCollectionViewCell *cell;
float randomRed,randomGreen,randomBlue;
}
- (void)viewDidLoad {
randomRed = arc4random() % 255;
randomGreen = arc4random() % 255;
randomBlue = arc4random() % 255;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"DisplayCellIphone" forIndexPath:indexPath];
if (indexPath.row == _setRandomIndex) {
// For Selected Color
cell.layer.backgroundColor = [UIColor colorWithRed:randomRed * 0.9 /255.0 green:randomGreen * 0.9 /255.0 blue:randomBlue * 0.9/255.0 alpha:1].CGColor;
} else {
cell.backgroundColor = [UIColor colorWithRed:randomRed/255.0 green:randomGreen/255.0 blue:randomBlue/255.0 alpha:1.0];
}
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
_count ++;
randomRed = arc4random() % 255;
randomGreen = arc4random() % 255;
randomBlue = arc4random() % 255;
if (indexPath.row == _setRandomIndex) {
if (_count == 0) {
[self addData:4];
}
NSLog(@"Selected Right Cell");
if (_count == 1 || _count == 2) {
_setRandomIndex = arc4random() % 6;
[self addData:6];
// _setRandomIndex = 2;
}
// next cell till 20;
}
答案 0 :(得分:0)
您可以使用[UIColor colorWithHue: saturation: brightness: alpha:]
并更改亮度和饱和度值。设置参数的随机值,并使用此文章中的答案获取UIColor的组件,并通过仅更改亮度和饱和度值来保持色调值不变来生成颜色
Is there function to convert UIColor to Hue Saturation Brightness?
答案 1 :(得分:0)
首先保留UIColor
属性(我将其命名为cellColor
)并使用下面的代码
if (indexpath.row ==1) {
CGFloat hue = ( arc4random() % 256 / 256.0 ); // 0.0 to 1.0
CGFloat saturation = ( arc4random() % 128 / 256.0 ) + 0.5; // 0.5 to 1.0, away from white
CGFloat brightness = ( arc4random() % 128 / 256.0 ) + 0.5; // 0.5 to 1.0, away from black
self.cellColor = [UIColor colorWithHue:hue saturation:saturation brightness:brightness alpha:1];
}
if (indexpath.row == 2) {
CGFloat hue, saturation, brightness, alpha;
BOOL success = [self.cellColor getHue:&hue saturation:&saturation brightness:&brightness alpha:&alpha];
self.cellColor = [self.cellColor initWithHue:hue saturation:saturation/2 brightness:brightness alpha:alpha;
}
现在,在indexPath 1条件下,您可以创建随机颜色。在indexPath 2条件下,我得到了色调和饱和度值,并将随机颜色的饱和度值更改为更亮。 我希望这可以帮到你。