如何在iOS

时间:2018-02-20 12:43:22

标签: ios swift uibezierpath drawrect

如何在UIView中添加虚线?

我的代码:

let  path = UIBezierPath()

let  p0 = CGPointMake(CGRectGetMinX(view.bounds),
                              CGRectGetMidY(view.bounds))
path.moveToPoint(p0)

let  p1 = CGPointMake(CGRectGetMaxX(view.bounds),
                              CGRectGetMidY(view.bounds))
path.addLineToPoint(p1)

let  dashes: [ CGFloat ] = [ 16.0, 32.0 ]
path.setLineDash(dashes, count: dashes.count, phase: 0.0)

path.lineWidth = 8.0
path.lineCapStyle = .Butt
UIColor.magentaColor().set()
path.stroke()
view.setNeedsDisplay()

但它没有显示任何内容。

我在日志中得到这个:

  

CGContextSetLineDash:无效的上下文0x0。如果你想查看回溯,请设置CG_CONTEXT_SHOW_BACKTRACE环境变量。

3 个答案:

答案 0 :(得分:2)

试试这个。

let rect = CGRect.init(origin: CGPoint.init(x: 0, y: 0), size: CGSize.init(width: 180, height: 180))//Set Height width as you want
let layer = CAShapeLayer.init()
let path = UIBezierPath(roundedRect: rect, cornerRadius: 8)
layer.path = path.cgPath;
layer.strokeColor = UIColor(red: 205/255, green: 207/255, blue: 211/255, alpha: 1.0).cgColor; // Set Dashed line Color
layer.lineDashPattern = [7,7]; // Here you set line length
layer.backgroundColor = UIColor.clear.cgColor;
layer.fillColor = UIColor.clear.cgColor;
self.newView.layer.addSublayer(layer);  

希望它会有所帮助!

答案 1 :(得分:0)

使用以下代码将虚线添加到父视图中。

for index in 0 ..< 10 {
  let frame : CGRect = CGRectMake(index*10,200,2,30)
  var subview : UIView = UIView(frame: frame)
  testView.backgroundColor = UIColor.gray
  testView.alpha=1.0
  self.view.addSubview(testView)
}

答案 2 :(得分:0)

这对我有用,我创造了一个盒子并给出了例如1并添加了虚线 CAShapeLayer

let line = CAShapeLayer()

let rect = CGRect(x: /*X position*/, y: /*Y position */, width: /*X width of line*/, height: /*height of line*/)

line.path = UIBezierPath(roundedRect: view.bounds, cornerRadius:0).cgPath
line.frame = self.bounds
line.strokeColor = UIColor.lightGray.cgColor
line.fillColor = UIColor.lightGray.cgColor
line.lineDashPattern = [4, 4]
view.layer.addSublayer(line)

希望有所帮助!!