swift-绘制虚线
2017-09-12 本文已影响53人
一蓑丨烟雨
参考:http://www.jianshu.com/p/f9009968c735
效果图:
虚线边框.png
代码:
//绘制虚线边框
func addDashdeBorderLayer(byView view:UIView, color:UIColor,lineWidth width:CGFloat){
let shapeLayer = CAShapeLayer()
let size = view.frame.size
let shapeRect = CGRectMake(10, 10, size.width-20, size.height-20)
shapeLayer.bounds = shapeRect
shapeLayer.position = CGPoint(x: size.width*0.5, y: size.height*0.5)
shapeLayer.fillColor = UIColor.clear.cgColor
shapeLayer.strokeColor = color.cgColor
shapeLayer.lineWidth = width
shapeLayer.lineJoin = kCALineJoinRound
//
shapeLayer.lineDashPattern = [3,4]
let path = UIBezierPath(roundedRect: shapeRect, cornerRadius: 5)
shapeLayer.path = path.cgPath
view.layer.addSublayer(shapeLayer)
}
效果图2:
虚线2.png
代码:
func addDashdeBorderLayer(by view:UIView){
let imgV:UIImageView = UIImageView(frame: CGRect(x: 0, y: view.sizeHeight-5, width: view.sizeWidth, height: 5))
view.addSubview(imgV)
UIGraphicsBeginImageContext(imgV.frame.size)
let context = UIGraphicsGetCurrentContext()
context?.setLineCap(CGLineCap.square)
let lengths:[CGFloat] = [10,30,]
context?.setStrokeColor(UIColor.red.cgColor)
context?.setLineWidth(2)
context?.setLineDash(phase: 0, lengths: lengths)
context?.move(to: CGPoint(x: 0, y: 3))
context?.addLine(to: CGPoint(x: view.sizeWidth, y: 3))
context?.strokePath()
context?.setStrokeColor(UIColor.blue.cgColor)
context?.setLineWidth(2)
context?.setLineDash(phase: 0, lengths: lengths)
context?.move(to: CGPoint(x: 20, y: 3))
context?.addLine(to: CGPoint(x: view.sizeWidth, y: 3))
context?.strokePath()
imgV.image = UIGraphicsGetImageFromCurrentImageContext()
//结束
UIGraphicsEndImageContext()
}