我已经对 UIView 进行了子类化,并且实现了一个 drawRect 。我基本上希望在设置 CGPoint(这是此 UIView 的一个属性)之后调用此 drawRect。我该怎么做呢?这是我的代码:
-(id) initWithCoder:(NSCoder *)aDecoder
{
if(self = [super initWithCoder:aDecoder]) {
point_.x = 0;
self.page_ = [UIImage imageNamed:@"pages"];
}
return self;
}
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
if (point_.x != 0){
[self.page_ drawInRect:rect];
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetStrokeColorWithColor(context, [UIColor blackColor].CGColor);
CGContextSetLineWidth(context, 1.0f);
CGContextMoveToPoint(context, 40, point_.y);
CGContextAddLineToPoint(context, 420, point_.y);
CGContextStrokePath(context);
}
}
当我设置了这个 UIView 的点并在另一个 UIViewController 中调用 drawRect 时,如下所示:
self.page_.point_ = CGPointMake(-100, self.title_.frameHeight + self.title_.frameX + 40);
[self.page_ drawRect:self.page_.frame];
它给了我所有这些错误:
<Error>: CGContextSaveGState: invalid context 0x0
Feb 22 20:24:38 <Error>: CGContextSetBlendMode: invalid context 0x0
Feb 22 20:24:38 <Error>: CGContextSetAlpha: invalid context 0x0
Feb 22 20:24:38 <Error>: CGContextTranslateCTM: invalid context 0x0
Feb 22 20:24:38 <Error>: CGContextScaleCTM: invalid context 0x0
Feb 22 20:24:38 <Error>: CGContextDrawImage: invalid context 0x0
Feb 22 20:24:38 <Error>: CGContextRestoreGState: invalid context 0x0
Feb 22 20:24:38 <Error>: CGContextSetStrokeColorWithColor: invalid context 0x0
Feb 22 20:24:38 <Error>: CGContextSetLineWidth: invalid context 0x0
Feb 22 20:24:38 <Error>: CGContextMoveToPoint: invalid context 0x0
Feb 22 20:24:38 <Error>: CGContextAddLineToPoint: invalid context 0x0
Feb 22 20:24:38 <Error>: CGContextDrawPath: invalid context 0x0
为什么是这样?
你永远不应该打电话-drawRect:
直接地。
Use -setNeedsDisplay
反而:
self.page_.point_ = CGPointMake(-100, self.title_.frameHeight + self.title_.frameX + 40);
[self.page_ setNeedsDisplay];
如果您需要自定义绘图区域(又名CGRect
这将被传递到-drawRect:
), 您可以使用-setNeedsDisplayInRect:
As @罗布·梅奥夫 https://stackoverflow.com/users/77567/rob-mayoff已建议,您可以覆盖设置器point_
财产:
- (void)setPoint_:(CGPoint)point {
if(!CGPointEqualToPoint(point_, point)) {
point_ = point;
[self setNeedsDisplay];
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)