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