绘制animation
我正在创build一个简单的应用程序,当用户按下button时,屏幕上会绘制一系列线条,用户将能够实时看到这些线条(几乎就像animation一样)。
我的代码看起来像这样(已简化):
UIGraphicsBeginImageContext(CGSizeMake(300,300)); CGContextRef context = UIGraphicsGetCurrentContext(); for (int i = 0; i < 100; i++ ) { CGContextMoveToPoint(context, i, i); CGContextAddLineToPoint(context, i+20, i+20); CGContextSetStrokeColorWithColor(context, [[UIColor blackColor] CGColor]); CGContextStrokePath(context); } UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext();
我的问题是:
1)只要用户按下button,UIThread就会阻塞,直到完成绘制。
2)我无法一次一个地在屏幕上绘制线条 – 我试图直接在循环内设置UIImage,并尝试在循环内设置图层内容。
我如何解决这些问题?
你说“就像一个animation”。 为什么不做一个实际的animation,一个la Core Graphics的CABasicAnimation
? 你真的需要把它作为一系列的线条,或者是一个适当的animation好吗?
如果你想animation的线条的实际绘制,你可以做这样的事情:
#import <QuartzCore/QuartzCore.h> - (void)drawBezierAnimate:(BOOL)animate { UIBezierPath *bezierPath = [self bezierPath]; CAShapeLayer *bezier = [[CAShapeLayer alloc] init]; bezier.path = bezierPath.CGPath; bezier.strokeColor = [UIColor blueColor].CGColor; bezier.fillColor = [UIColor clearColor].CGColor; bezier.lineWidth = 5.0; bezier.strokeStart = 0.0; bezier.strokeEnd = 1.0; [self.view.layer addSublayer:bezier]; if (animate) { CABasicAnimation *animateStrokeEnd = [CABasicAnimation animationWithKeyPath:@"strokeEnd"]; animateStrokeEnd.duration = 10.0; animateStrokeEnd.fromValue = [NSNumber numberWithFloat:0.0f]; animateStrokeEnd.toValue = [NSNumber numberWithFloat:1.0f]; [bezier addAnimation:animateStrokeEnd forKey:@"strokeEndAnimation"]; } }
那么你所要做的就是为你的行创buildUIBezierPath
,例如:
- (UIBezierPath *)bezierPath { UIBezierPath *path = [UIBezierPath bezierPath]; [path moveToPoint:CGPointMake(0.0, 0.0)]; [path addLineToPoint:CGPointMake(200.0, 200.0)]; return path; }
如果你愿意的话,你可以将一堆线条拼凑成一条path,例如这里是一个大致的正弦曲线形状的系列线条:
- (UIBezierPath *)bezierPath { UIBezierPath *path = [UIBezierPath bezierPath]; CGPoint point = self.view.center; [path moveToPoint:CGPointMake(0, self.view.frame.size.height / 2.0)]; for (CGFloat f = 0.0; f < M_PI * 2; f += 0.75) { point = CGPointMake(f / (M_PI * 2) * self.view.frame.size.width, sinf(f) * 200.0 + self.view.frame.size.height / 2.0); [path addLineToPoint:point]; } return path; }
而这些不会阻塞主线程。
顺便说一句,您显然必须将CoreGraphics.framework
添加到目标的Build Settings
Link Binary With Libraries
Build Settings
下的“ Build Settings
。