Search code examples
iosobjective-carc4random

Objective-C: Drawing Random Circle Sizes


I am working on a Game Application involving circles. How can I edit the code below to "draw" randomly sized black circles? At the moment it gets an image file set called Dot but I don't want to be limited by that + the resolution wouldn't be good on all devices.

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

Solution

  • Something like this should work for you:

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

    You would call it with something like this (I have not tested this):

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