gpt4 book ai didi

ios - 为什么这种随机颜色方法不起作用?

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:30:05 24 4
gpt4 key购买 nike

我在 drawRect 方法中有一个 for 循环,它绘制了许多圆圈来填充屏幕。我正在努力使每个圆圈都有一个新的随机笔划。由于某种原因,什么都没有出现。这是我的 randomColor 方法:

    -(UIColor *) randomColor
{
int red, green, blue, alpha;

red = arc4random_uniform(255);
green = arc4random_uniform(255);
blue = arc4random_uniform(255);
alpha = arc4random_uniform(255);

UIColor *colorToReturn = [[UIColor alloc] initWithRed:red green:green blue:blue alpha:alpha];

return colorToReturn;
}

我尝试在这里实现它:

-(void) drawRect:(CGRect)rect
{
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGRect bounds = [self bounds];

// Firgure out the center of the bounds rectangle
CGPoint center;
center.x = bounds.origin.x + bounds.size.width / 2.0;
center.y = bounds.origin.y + bounds.size.height / 2.0;

// The radius of the circle should be nearly as big as the view
float maxRadius = hypot(bounds.size.width, bounds.size.height) / 2.0;

// The thickness of the line should be 10 points wide
CGContextSetLineWidth(ctx, 10);

// The color of the line should be gray (red/green/blue = 0.6, alpha = 1.0)
// CGContextSetRGBStrokeColor(ctx, 0.6, 0.6, 0.6, 1.0);
// The same as
// [[UIColor colorWithRed:0.6 green:0.6 blue:0.6 alpha:1.0] setStroke];
// The same as

// [[UIColor redColor] setStroke];

// Draw concentric circles from the outside in
for (float currentRadius = maxRadius; currentRadius > 0; currentRadius -= 20) {
// Add a path to the context
CGContextAddArc(ctx, center.x, center.y, currentRadius, 0.0, M_PI * 2.0, YES);

[[self randomColor] setStroke];

// Perform drawing instructions; removes path
CGContextStrokePath(ctx);
}

最佳答案

UIColor 采用 0 到 1 之间的 float 作为其 RGB 分量的值:

 UIColor *colorToReturn = [[UIColor alloc] initWithRed:red/255.0 green:green/255.0 blue:blue/255.0 alpha:alpha];

关于ios - 为什么这种随机颜色方法不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17726919/

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