2012-08-23 139 views
3

我尝试在一个简单的UIView扩展中重写drawRect方法,以绘制一个带圆角边缘的矩形并用黑色填充它,并且还为该视图设置动画以调整触摸大小。 事情是,调整大小完全变形绘图,就好像上下文始终保持相同。 drawRect在动画过程中永远不会被调用。但是,如果我告诉视图在动画之后绘制它,它会正确绘制。iOS UIView 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); 
    }]; 
} 
+0

我胡乱猜测http://www.nomadplanet.fr/2010/11/animate-calayer- custom-properties-with-coreanimation/ – Jonny

回答

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

+1

同意 - 并确保你设置了'myView.clipsToBounds = YES;'。 – Ander

+0

是的,但是如果我想在该圆角矩形上绘制一些自定义效果怎么办? – Avahi

+0

你想达到什么样的其他效果 - 我的回答与你的问题有关... – tiguero