gpt4 book ai didi

ios - 如何在 Objective-C 中为 iOs 绘制随机矩形?

转载 作者:行者123 更新时间:2023-11-29 01:29:21 25 4
gpt4 key购买 nike

我想创建一个类,我们称它为 CustomView,我在其中编写了一个用于创建矩形的自定义方法。矩形的位置和大小应基于随机数。

这是我的 CustomView 到目前为止的样子:

自定义 View .m

#import "CustomView.h"

@implementation ShadowView

- (void)drawRect:(CGRect)rect {
int smallest = 0;
int largest = 100;
int r1 = smallest + arc4random() %(largest+1-smallest);
int r2 = smallest + arc4random() %(largest+1-smallest);

int smallest2 = 0;
int largest2 = 300;
int r3 = smallest + arc4random() %(largest2+1-smallest2);
int r4 = smallest + arc4random() %(largest2+1-smallest2);

// Drawing code
CGRect rectangle = CGRectMake(r1, r2, r3, r4);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetRGBFillColor(context, 1.0, 1.0, 1.0, 0.0);
CGContextSetRGBStrokeColor(context, 0.0, 0.0, 0.0, 0.5);
CGContextFillRect(context, rectangle);
CGContextStrokeRect(context, rectangle);
}

@end

自定义 View .h

#import <UIKit/UIKit.h>
@interface ShadowView : UIView

@end

现在,当我尝试通过 [CustomView drawRect] 在 ViewController.m 中调用此方法时,我只会收到错误消息吗?我做错了什么?

最佳答案

您不能在 ShadowView 上调用 drawRect:

您需要做的是创建一个 ShadowView 的实例,并将其添加到某个父 View 。就是这样。您不自己调用 drawRect:

ShadowView *view = [[ShadowView alloc] initWithFrame:CGRectMake(20, 20, 40, 50)]; // whatever frame you need
[self.view addSubview:view];

但是,考虑到您对 drawRect: 的实现,这并没有多大意义。看来您要制作的是一个随机大小和位置的矩形,然后填充白色并具有黑色边框。

这是另一个想法。更改 View 的 init 方法以给自己一个随机帧。

在 CustomView.m 中:

- (instancetype)init {
int smallest = 0;
int largest = 100;
int r1 = smallest + arc4random_uniform(largest+1-smallest);
int r2 = smallest + arc4random_uniform(largest+1-smallest);

int smallest2 = 0;
int largest2 = 300;
int r3 = smallest + arc4random_uniform(largest2+1-smallest2);
int r4 = smallest + arc4random_uniform(largest2+1-smallest2);

// Drawing code
CGRect rectangle = CGRectMake(r1, r2, r3, r4);

return [super initWithFrame:rectangle];
}

- (void)drawRect:(CGRect)rect {
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetRGBFillColor(context, 1.0, 1.0, 1.0, 0.0);
CGContextSetRGBStrokeColor(context, 0.0, 0.0, 0.0, 0.5);
CGContextFillRect(context, rect);
CGContextStrokeRect(context, rect);
}

现在,按如下方式创建和添加 View :

ShadowView *view = [[ShadowView alloc] init];
[self.view addSubview:view];

另请注意使用 arc4random_uniform 而不是 arc4random

假设您想添加 5 个这样的随机矩形,您可以这样做:

for (int i = 0; i < 5; i++) {
ShadowView *view = [[ShadowView alloc] init];
[self.view addSubview:view];
}

关于ios - 如何在 Objective-C 中为 iOs 绘制随机矩形?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33611816/

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