簡體   English   中英

如何在Objective-C for iO中繪制隨機矩形?

[英]How to draw random rectangles in Objective-C for iOs?

我想創建一個類,將其稱為CustomView ,在其中編寫用於創建矩形的自定義方法。 矩形的位置和大小應基於隨機數。

到目前為止,這是我的CustomView樣子:

CustomView.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

CustomView.h

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

@end

現在,當我嘗試通過[CustomView drawRect]在ViewController.m中調用此方法時,我只會得到錯誤? 我究竟做錯了什么?

您不能在ShadowView上調用drawRect: ShadowView

您需要做的是創建ShadowView的實例,並將其添加到某些父視圖中。 而已。 您不會自己調用drawRect:

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

但是,鑒於您對drawRect:的實現,這沒有多大意義。 您似乎要制作的是一個大小和位置隨機的矩形,然后用白色填充並帶有黑色邊框。

這是另一個想法。 更改視圖的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);
}

現在,創建並添加視圖,如下所示:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM