iOS UIView drawRect调整大小动画

时间:2012-08-23 05:32:28

标签: ios uiview core-animation drawrect

我试图在一个简单的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);
  }];
}

1 个答案:

答案 0 :(得分:2)

如果你想要UIView的圆边,你不需要显式重新定义drawRect。有一种更简单的方法可以更改UIView的图层属性。您的视图及其边框将在动画期间正确绘制。

// 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