Ios 目标C:绘制随机圆尺寸
我正在开发一个涉及圆圈的游戏应用程序。我如何编辑下面的代码来“绘制”随机大小的黑色圆圈?目前,它得到了一个名为Dot的图像文件集,但我不想受到这个限制,因为在所有设备上分辨率都不好Ios 目标C:绘制随机圆尺寸,ios,objective-c,arc4random,Ios,Objective C,Arc4random,我正在开发一个涉及圆圈的游戏应用程序。我如何编辑下面的代码来“绘制”随机大小的黑色圆圈?目前,它得到了一个名为Dot的图像文件集,但我不想受到这个限制,因为在所有设备上分辨率都不好 - (UIButton *)createNewButton { UIButton * clickMe = [[UIButton alloc] initWithFrame:CGRectMake(10, 10, 32, 32)]; [clickMe addTarget:self action:@sele
- (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;
}
您可以这样称呼它(我没有测试过):
我还是objective-c的“新手”,你能解释一下如何在我的代码中使用这个吗?
- (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;
}