我正在创建一个简单的应用程序,当用户按下按钮时,将在屏幕上绘制一系列线条,用户将能够看到实时绘制的这些线条(几乎像动画)。
我的代码看起来像这样(已简化):
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)一旦用户按下按钮,UIThread就会阻止,直到绘图完成。
2)我无法一次一个地在屏幕上绘制线条 - 我尝试直接在循环内设置UIImage,并尝试在循环内设置图层内容。
如何解决这些问题?
答案 0 :(得分:16)
你说“就像一个动画”。为什么不做一个真正的动画,一个核心图形'CABasicAnimation
?你真的需要将它显示为一系列线条,还是一个合适的动画好吗?
如果要为线条的实际绘制设置动画,可以执行以下操作:
#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"];
}
}
然后你要做的就是为你的行创建UIBezierPath
,例如:
- (UIBezierPath *)bezierPath
{
UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:CGPointMake(0.0, 0.0)];
[path addLineToPoint:CGPointMake(200.0, 200.0)];
return 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
。