简体   繁体   English

如何在 UIView 上绘制相同大小的虚线

[英]How to draw same size dotted line on UIView

Can someone please guide how I can draw same size dotted line on UIView for all sides?有人可以指导我如何在 UIView 上为所有侧面绘制相同大小的虚线吗?

I am using below code to draw line.我正在使用下面的代码来画线。

let dashBorder = CAShapeLayer()
let frameSize = self.frame.size
let shapeRect = CGRect(x: 0, y: 0, width: frameSize.width, height: frameSize.height)
dashBorder.bounds = shapeRect
dashBorder.position = CGPoint(x: frameSize.width/2, y: frameSize.height/2)
dashBorder.fillColor = UIColor.clear.cgColor
dashBorder.strokeColor = UIColor.blue.cgColor
dashBorder.lineJoin = CAShapeLayerLineJoin.round
dashBorder.lineDashPattern = [3, 3]
dashBorder.path = UIBezierPath(roundedRect: shapeRect, cornerRadius: 10.0).cgPath
layer.addSublayer(dashBorder)

在此处输入图像描述

It is shown as above如上图所示

as you can see the line width for left and right edge width are not same as top and bottom edge height.如您所见,左右边缘宽度的线宽与顶部和底部边缘高度不同。 Is there any way if I want to make same for all sides like below?如果我想为下面的所有面做同样的事情,有什么办法吗?

在此处输入图像描述

The trick is to inset the drawing frame with half the value of stroke width.诀窍是用笔划宽度值的一半插入绘图框。 Or half of your stroke will be clipped by the view, since bezier path centers the stroke to drawing line.或者一半的笔划将被视图剪裁,因为贝塞尔路径将笔划居中绘制线。

I also change your frame slightly and removed position.我还稍微改变了你的框架并移除了位置。 Here is the updated code.这是更新的代码。

    let lineWidth = 3.0
    let dashBorder = CAShapeLayer()
    let frameSize = bounds.insetBy(dx: lineWidth/2, dy: lineWidth/2)
    dashBorder.frame = bounds
    dashBorder.fillColor = UIColor.clear.cgColor
    dashBorder.strokeColor = UIColor.blue.cgColor
    dashBorder.lineJoin = CAShapeLayerLineJoin.round
    dashBorder.lineDashPattern = [3, 3]
    dashBorder.lineWidth = lineWidth
    dashBorder.path = UIBezierPath(roundedRect: frameSize, cornerRadius: 10.0).cgPath
    layer.addSublayer(dashBorder)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM