Objective-C:绘制随机圆形大小

时间:2015-03-01 20:21:07

标签: ios objective-c arc4random

我正在开发涉及圈子的游戏应用程序。如何编辑下面的代码来“绘制”随机大小的黑色圆圈?目前它获得了一个名为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;
}

1 个答案:

答案 0 :(得分:0)

这样的事情对你有用:

- (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;
}