我试图保存一个CGRect数组,以便与CGContextFillRects一起使用,但是我分配给CGContextFillRects数组的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);
}发布于 2016-06-08 22:27:07
我尝试将您的代码(构造minorPlotLines的内容,然后将内容读入另一个项目)拉到另一个项目中,它似乎很好地保存了这些内容,因此基本代码本身似乎还不错。
我将检查以确保在构建数组minorPlotLines (即在-setupView中)时,确实有一个非零帧。在类只是部分构造(例如UIViewController类的回调-viewDidLoad)时调用早期UI类加载回调是很常见的,这使您别无选择,只能将某些决定推迟到加载过程的后期。特别是布局在游戏中发生得相对较晚,而且由于您的-setupView方法在-init方法中被调用,我猜框架还没有为类提供任何布局,因此它没有可用的框架(也就是说,您的框架实际上相当于CGRectZero)。
https://stackoverflow.com/questions/37711133
复制相似问题