使用CALayer绘制虚线 [英] drawing dashed line using CALayer

查看:538
本文介绍了使用CALayer绘制虚线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我能够使用以下代码绘制虚线框:

I was able to draw a dashed box, using the following code:

CAShapeLayer *shapeLayer = [CAShapeLayer layer];
CGRect shapeRect = CGRectMake(0.0f, 0.0f, 200.0f, 100.0f);
[shapeLayer setBounds:shapeRect];
[shapeLayer setPosition:CGPointMake(self.coreImageView_.frameX, self.coreImageView_.frameBottom - self.coreImageView_.frameHeight/2)];
[shapeLayer setFillColor:[[UIColor clearColor] CGColor]];
[shapeLayer setStrokeColor:[[UIColor whiteColor] CGColor]];
[shapeLayer setLineWidth:2.0f];
[shapeLayer setLineJoin:kCALineJoinRound];
[shapeLayer setLineDashPattern:
[NSArray arrayWithObjects:[NSNumber numberWithInt:5],
[NSNumber numberWithInt:5],
  nil]];

现在如果我想从X点到B点画一条虚线,我应该如何修改这段代码?

Now if I want to just draw a dashed line from point X to point B, how should I modify this code?

推荐答案

首先将路径移动到线的起点,然后添加线段来绘制线条。一点:

Lines are drawn by first moving the path to a starting point of the line, then adding a line segment to a point:

CGContextBeginPath(context);
CGContextMoveToPoint(context, 10.5f, 10.5f);
CGContextAddLineToPoint(context, 20.5f, 20.5f);
CGContextClosePath(context);
CGContextDrawPath(context, kCGPathFillStroke);

对于绘制虚线,您需要使用CAShapeLayer

For drawing dashed line, You need to use CAShapeLayer

CAShapeLayer *shapeLayer = [CAShapeLayer layer];
[shapeLayer setBounds:self.bounds];
[shapeLayer setPosition:self.center];
[shapeLayer setFillColor:[[UIColor clearColor] CGColor]];
[shapeLayer setStrokeColor:[[UIColor blackColor] CGColor]];
[shapeLayer setLineWidth:3.0f];
[shapeLayer setLineJoin:kCALineJoinRound];
[shapeLayer setLineDashPattern:
 [NSArray arrayWithObjects:[NSNumber numberWithInt:10],
  [NSNumber numberWithInt:5],nil]];

// Setup the path
CGMutablePathRef path = CGPathCreateMutable();
CGPathMoveToPoint(path, NULL, 10, 10);
CGPathAddLineToPoint(path, NULL, 100,100);

[shapeLayer setPath:path];
CGPathRelease(path);

[[self layer] addSublayer:shapeLayer];

这篇关于使用CALayer绘制虚线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆