HHH*_*HHH 6 iphone xcode quartz-graphics drawrect ios
我正在创建一个简单的应用程序,当用户按下按钮时,将在屏幕上绘制一系列线条,用户将能够看到实时绘制的这些线条(几乎像动画).
我的代码看起来像这样(已经简化):
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();
Run Code Online (Sandbox Code Playgroud)
我的问题是:
1)一旦用户按下按钮,UIThread就会阻塞,直到绘图完成.
2)我无法一次一个地在屏幕上绘制线条 - 我尝试直接在循环内设置UIImage,并尝试在循环内设置图层内容.
我该如何解决这些问题?
Rob*_*Rob 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"];
}
}
Run Code Online (Sandbox Code Playgroud)
然后你所要做的就是UIBezierPath为你的线创建,例如:
- (UIBezierPath *)bezierPath
{
UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:CGPointMake(0.0, 0.0)];
[path addLineToPoint:CGPointMake(200.0, 200.0)];
return path;
}
Run Code Online (Sandbox Code Playgroud)
如果你愿意,你可以将一堆线拼凑成一条路径,例如这里是一个大致正弦曲线形状的系列线:
- (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;
}
Run Code Online (Sandbox Code Playgroud)
而这些不会阻止主线程.
顺便说一下,你显然必须将CoreGraphics.framework你的目标添加到你的目标Build Settings之下Link Binary With Libraries.
| 归档时间: |
|
| 查看次数: |
4333 次 |
| 最近记录: |