adi*_*dit 21 iphone objective-c ipad ios
我能够使用以下代码绘制一个虚线框:
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]];
Run Code Online (Sandbox Code Playgroud)
现在如果我想从点X到点B绘制一条虚线,我该如何修改这段代码呢?
Lit*_*T.V 55
通过首先将路径移动到线的起点,然后将线段添加到点来绘制线:
CGContextBeginPath(context);
CGContextMoveToPoint(context, 10.5f, 10.5f);
CGContextAddLineToPoint(context, 20.5f, 20.5f);
CGContextClosePath(context);
CGContextDrawPath(context, kCGPathFillStroke);
Run Code Online (Sandbox Code Playgroud)
对于绘制虚线,您需要使用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];
Run Code Online (Sandbox Code Playgroud)
试试这个代码,它对我有用
斯威夫特3.0
extension UIView {
func addDashedLine(strokeColor: UIColor, lineWidth: CGFloat) {
backgroundColor = .clear
let shapeLayer = CAShapeLayer()
shapeLayer.name = "DashedTopLine"
shapeLayer.bounds = bounds
shapeLayer.position = CGPoint(x: frame.width / 2, y: frame.height / 2)
shapeLayer.fillColor = UIColor.clear.cgColor
shapeLayer.strokeColor = strokeColor.cgColor
shapeLayer.lineWidth = lineWidth
shapeLayer.lineJoin = kCALineJoinRound
shapeLayer.lineDashPattern = [4, 4]
let path = CGMutablePath()
path.move(to: CGPoint.zero)
path.addLine(to: CGPoint(x: frame.width, y: 0))
shapeLayer.path = path
layer.addSublayer(shapeLayer)
}
}
Run Code Online (Sandbox Code Playgroud)
看到:
CGFloat dashLengths[] = { 10, 5 };
CGContextSetLineDash(context, 0, dashLengths, 2);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
32090 次 |
| 最近记录: |