gpt4 book ai didi

iOS:如何生成随机柔和的颜色?

转载 作者:塔克拉玛干 更新时间:2023-11-02 10:32:33 26 4
gpt4 key购买 nike

如何为 iOS 生成漂亮的柔和色彩?

这里有 David Crow 用 Ja​​va 编写的精彩丰富的答案:Algorithm to randomly generate an aesthetically-pleasing color palette

那么我们如何适配 iOS 呢?

最佳答案

John Coates 的 Swift 实现出现在这里:https://gist.github.com/JohnCoates/725d6d3c5a07c4756dec但他错误地称其为“粉彩”,尽管不包括实现该效果所需的浅蓝色。

我的 John 的 git(混合了淡蓝色)的 Objective-C 版本在这里:

// Adapted from Stack Overflow answer by David Crow http://stackoverflow.com/a/43235
-(UIColor*) generateRandomPastelColor
{
// Randomly generate numbers
CGFloat red = ( (CGFloat)(arc4random() % 256) ) / 256;
CGFloat green = ( (CGFloat)(arc4random() % 256) ) / 256;
CGFloat blue = ( (CGFloat)(arc4random() % 256) ) / 256;

// Mix with light-blue
CGFloat mixRed = 1+0xad/256, mixGreen = 1+0xd8/256, mixBlue = 1+0xe6/256;
red = (red + mixRed) / 3;
green = (green + mixGreen) / 3;
blue = (blue + mixBlue) / 3;
return [UIColor colorWithRed:red green:green blue:blue alpha:1];
}

编辑

我改进了算法,通过将白色也混合到计算中(通过将 1 加到浅蓝色并减少 3 而不是 2),使颜色更亮。

下面是上述方法的测试代码(可以替换成新项目的viewDidLoad运行):

#define RECT_SIZE 30

- (void)viewDidLoad {
[super viewDidLoad];
CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width;
CGFloat screenHeight = [UIScreen mainScreen].bounds.size.height;
int horizontals = screenWidth / RECT_SIZE;
int verticals = screenHeight / RECT_SIZE;
float offset_h = ((int)screenWidth % RECT_SIZE)/2;
float offset_v = ((int)screenHeight % RECT_SIZE)/2;
for (int v=0; v < verticals; v++) {
for (int h=0; h < horizontals; h++) {
CGRect rect = CGRectMake(offset_h + h * RECT_SIZE, offset_v + v * RECT_SIZE, RECT_SIZE, RECT_SIZE);
UIView *square = [[UIView alloc] initWithFrame:rect];
square.backgroundColor = [self generateRandomPastelColor];
[self.view addSubview:square];
}
}
}

关于iOS:如何生成随机柔和的颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36617427/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com