【问题标题】:How to add dashed line inside view in iOS如何在iOS中的视图内添加虚线
【发布时间】:2018-02-20 12:43:22
【问题描述】:

如何在 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 环境变量。

【问题讨论】:

标签: ios swift uibezierpath drawrect


【解决方案1】:

试试这个。

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);  

希望对您有所帮助!

【讨论】:

  • 省略.inits以获得更简洁的代码,例如:let rect = CGRect(origin: CGPoint(x:0, y:0), size: CGSize(width:180, height:180))
【解决方案2】:

使用下面的代码将虚线添加到您的父视图。

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)
}

【讨论】:

    【解决方案3】:

    这对我有用,我创建了一个盒子并给出了例如高度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)
    

    希望有帮助!!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-29
      • 1970-01-01
      • 2012-04-05
      • 2018-08-27
      • 2013-09-16
      • 1970-01-01
      相关资源
      最近更新 更多