Objective-C:绘制随机圆大小

Objective-C: Drawing Random Circle Sizes

我正在开发一个涉及圆圈的游戏应用程序。如何将下面的代码编辑为 "draw" 随机大小的黑色圆圈?目前它有一个名为 Dot 的图像文件集,但我不想受限于此 + 分辨率在所有设备上都不好。

- (UIButton *)createNewButton {

    UIButton * clickMe = [[UIButton alloc] initWithFrame:CGRectMake(10, 10, 32, 32)];
    [clickMe addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
    [clickMe setBackgroundImage:[UIImage imageNamed:@"Dot"] forState:UIControlStateNormal];
    [self.view addSubview:clickMe];

    CGRect buttonFrame = clickMe.frame;
    int randomX = arc4random() % (int)(self.view.frame.size.width - buttonFrame.size.width);
    int randomY = arc4random() % (int)(self.view.frame.size.height - buttonFrame.size.height);

    buttonFrame.origin.x = randomX;
    buttonFrame.origin.y = randomY;
    clickMe.frame = buttonFrame;
    return clickMe;
}

像这样的东西应该适合你:

- (UIImage *)createCircleOfColor:(UIColor *)color size:(CGSize)size
{
    UIGraphicsBeginImageContext(size);
    CGContextRef context = UIGraphicsGetCurrentContext();

    CGRect targetRect = CGRectMake(0, 0, size.width, size.height);
    CGContextSetFillColorWithColor(context, [UIColor clearColor].CGColor);
    CGContextFillRect(context, targetRect);

    CGContextSetFillColorWithColor(context, color.CGColor);
    CGContextFillEllipseInRect(context, targetRect);

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return image;
}

你可以这样称呼它(我还没有测试过):

- (UIButton *)createNewButton {

    UIButton *clickMe = [[UIButton alloc] initWithFrame:CGRectZero];
    [clickMe addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:clickMe];

    CGRect buttonFrame = clickMe.frame;
    CGFloat randomX = arc4random_uniform((u_int32_t)(self.view.frame.size.width - buttonFrame.size.width));
    CGFloat randomY = arc4random_uniform((u_int32_t)(self.view.frame.size.height - buttonFrame.size.height));

    CGFloat randomWH = arc4random_uniform(20);  // Or whatever you want the max size to be.
    CGSize randomSize = CGSizeMake(randomWH, randomWH);
    UIImage *randomCircleImage = [self createCircleOfColor:[UIColor blueColor] size:randomSize];
    [clickMe setBackgroundImage:randomCircleImage forState:UIControlStateNormal];

    buttonFrame.origin.x = randomX;
    buttonFrame.origin.y = randomY;
    buttonFrame.size = randomSize;
    clickMe.frame = buttonFrame;
    return clickMe;
}