0

This might be a simple one. I am trying to create multiple UIView with different colors using a For-loop:

float colorGrade = 255.0 / 160;

for (int i = 0; i < 160; i++)
{
    float finalColor = colorGrade * i;
    if (finalColor > 255)
        finalColor = 255;

    UIView *viewColor = [[UIView alloc] initWithFrame:CGRectMake(i * 2, 0, 2, viewHeight)];
    UIColor *bgColor = [UIColor colorWithRed:finalColor green:0 blue:0 alpha:1];
    [viewColor setAlpha:1];
    [viewColor setBackgroundColor:bgColor];
    [viewColor setTag:i + 1];

    [touchPadView addSubview:viewColor];
}

Views are created, but they are all ended up with the same colors. Something is missing here?

Thanks.

4

3 回答 3

1

做这个

UIColor *bgColor = [UIColor colorWithRed:finalColor/255.0 green:0.0 blue:0.0 alpha:1.0];
于 2013-05-28T09:56:19.877 回答
1

尝试使用这个。因为您的 UIColor 方法需要从 0-1 的浮点数,而不是 0-255。您需要将所有 RGB 值除以 255.0。

float colorGrade = 255.0 / 160;

for (int i = 0; i < 160; i++)
{
    float finalColor = colorGrade * i;
    if (finalColor > 255)
        finalColor = 255;

    UIView *viewColor = [[UIView alloc] initWithFrame:CGRectMake(i * 2, 0, 2, viewHeight)];
    UIColor *bgColor = [UIColor colorWithRed:finalColor/255.0f green:0.0f blue:0 alpha:1];
    [viewColor setAlpha:1];
    [viewColor setBackgroundColor:bgColor];
    [viewColor setTag:i + 1];

    [touchPadView addSubview:viewColor];
}
于 2013-05-28T09:57:18.960 回答
0
UIColor *bgColor = [UIColor colorWithRed:finalColor/255.0f green:0 blue:0 alpha:1];

将行更改为上面。

于 2013-05-28T09:57:20.777 回答