iOS UIView drawRect重绘大小动画

3
我尝试在简单的UIView扩展中覆盖drawRect方法,以绘制一个具有圆角的矩形,并用黑色填充它,还要通过触摸来动画调整视图大小。问题是,调整大小会完全改变绘图,就好像整个时间上下文保持不变一样。在动画期间,drawRect从未被调用。但是,如果我告诉视图在动画之后绘制自己,则可以正确绘制。如何在不使绘图变形的情况下对调整大小进行动画处理?
- (void)drawRect:(CGRect)rect {
  CGContextRef context = UIGraphicsGetCurrentContext();  
  CGFloat radius = rect.size.height * 0.5f;  

  CGMutablePathRef path = CGPathCreateMutable();

  CGPathMoveToPoint(path, NULL, CGRectGetMidX(rect), CGRectGetMinY(rect));
  CGPathAddArcToPoint(path, NULL, CGRectGetMaxX(rect), CGRectGetMinY(rect), 
                  CGRectGetMaxX(rect), CGRectGetMaxY(rect), radius);
  CGPathAddArcToPoint(path, NULL, CGRectGetMaxX(rect), CGRectGetMaxY(rect), 
                  CGRectGetMinX(rect), CGRectGetMaxY(rect), radius);
  CGPathAddArcToPoint(path, NULL, CGRectGetMinX(rect), CGRectGetMaxY(rect), 
                  CGRectGetMinX(rect), CGRectGetMinY(rect), radius);
  CGPathAddArcToPoint(path, NULL, CGRectGetMinX(rect), CGRectGetMinY(rect), 
                  CGRectGetMaxX(rect), CGRectGetMinY(rect), radius);
  CGPathCloseSubpath(path);

  CGContextSaveGState(context);
  CGContextSetFillColorWithColor(context, [UIColor blackColor].CGColor);
  CGContextAddPath(context, path);
  CGContextFillPath(context);
  CGContextRestoreGState(context);
}


- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
  [UIView animateWithDuration:1.f animations:^{
    self.frame = CGRectInset(self.frame, 0.f, -100.f);
  }];
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
  [UIView animateWithDuration:1.f animations:^{
    self.frame = CGRectInset(self.frame, 0.f, +100.f);
  }];
}

我猜测这里是http://www.nomadplanet.fr/2010/11/animate-calayer-custom-properties-with-coreanimation/。 - Jonny
1个回答

2

如果你想让一个UIView有圆角边缘,你不需要显式地重新定义drawRect。有一种更简单的方法是改变你的UIView的layer属性。在动画期间,你的视图及其边框将被正确绘制。

// Make your view background color black
myView.backgroundColor = [UIColor blackColor];

// The following will allow you to change the color/border width/ corner radius of your UIView
myView.layer.borderColor  = [UIColor whiteColor].CGColor;
myView.layer.borderWidth  = kDefaultBorderWidth;
myView.layer.cornerRadius = kDefaultBorderRadius;

请确保您在.m文件中已经包含了#import <QuartzCore/QuartzCore.h>,并且已经导入了QuartzCore.framework


1
同意 - 并确保设置 myView.clipsToBounds = YES; - Ander
是的,但如果我想在那个圆角矩形上绘制一些自定义效果怎么办? - Avahi
你想要实现什么其他效果 - 我的回答与你的问题有关... - tiguero
根据这篇文章,drawrect只适用于某一时刻,因此它无法与动画一起使用。 - tiguero

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接