0

我正在尝试保存一个 CGRect 数组以与 CGContextFillRects 一起使用,但我分配给我的 minorPlotLines 数组的 CGRect 变量似乎没有得到保存。到这里的对象自己绘制的时候,minorPlotLines 是空的!有谁知道发生了什么?

@interface GraphLineView () {
    int numberOfLines;
    CGRect *minorPlotLines;
}


@end


@implementation GraphLineView


- (instancetype) initWithFrame: (CGRect) frame {
    self = [super initWithFrame:frame];
    if (self) {
        // Init code
        [self setupView];
    }
    return self;
}

- (instancetype) initWithCoder: (NSCoder *) aDecoder {
    if(self == [super initWithCoder:aDecoder]){
        [self setupView];
    }
    return self;
}

- (void) dealloc {
    free(minorPlotLines);
}

- (void) setupView {

    numberOfLines = 40;
    minorPlotLines = malloc(sizeof(struct CGRect)*40); 

    for(int x = 0; x < numberOfLines; x += 2){
        //minorPlotLines[x] = *(CGRect*)malloc(sizeof(CGRect));
        minorPlotLines[x] = CGRectMake(x*(self.frame.size.width/numberOfLines), 0, 2, self.frame.size.height);

       // minorPlotLines[x+1] = *(CGRect*)malloc(sizeof(CGRect));
        minorPlotLines[x+1] = CGRectMake(0, x*(self.frame.size.height/numberOfLines), self.frame.size.width, 2);

    }

    [self setNeedsDisplay];
}

- (void) drawRect:(CGRect)rect {
    // Drawing code
    [super drawRect:rect];

    for(int x = 0; x < numberOfLines; x += 2){
        NSLog(@"R %d = %f", x, minorPlotLines[x].origin.x);
        NSLog(@"R %d = %f", x+1, minorPlotLines[x+1].origin.y);
    }

    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [[UIColor yellowColor] CGColor]);
    CGContextFillRects(context, minorPlotLines, numberOfLines);

}
4

1 回答 1

1

我尝试将您的代码(构造内容minorPlotLines并稍后将内容读回)拉到另一个项目中,它似乎确实很好地保留了内容,因此您的基本代码本身看起来很合理。

我会检查以确保您在构建数组时实际上有一个非零帧minorPlotLines(即 in -setupView)。在您的类仅部分构造(例如 UIViewController 类的回调)时调用早期 UI 类加载回调是很常见的-viewDidLoad,这让您别无选择,只能将某些决定推迟到加载过程的后期。尤其是布局在游戏中发生的相对较晚,并且由于您的-setupView方法是在一个-init方法中直接调用的,我猜该框架尚未为您的类提供任何布局,因此它没有可用的框架(即您的框架有效相当于CGRectZero)。

于 2016-06-08T22:27:07.117 回答