ios - 如何在 iOS View 中添加虚线

标签 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: invalid context 0x0. If you want to see the backtrace, please set CG_CONTEXT_SHOW_BACKTRACE environmental variable.

最佳答案

试试这个。

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

希望对您有所帮助!

关于ios - 如何在 iOS View 中添加虚线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48885568/

相关文章:

ios - 如何确定View的背景颜色?

ios - 联合 UIBezierPath 而不是追加路径

ios - 使用小数点声明 UIBezierPath 是否有意义?

ios - 如何在 swift 4 IOS 中从 TableViewController 的 "viewForHeaderInSection"方法设置 UITableViewHeaderFooterView 的属性?

objective-c - 监视目录时dispatch_source_get_data不返回正确的标志

ios - Swift:自定义部分标题包含用于删除行或仅为该部分的行添加行的按钮

ios - 从 CGContextRef 获取 UIBezierPath 或 CGPath

ios - 如何删除 UIBarButtonItem 的左填充?

ios - UIImageView 拖放到另一个上

swift - 准备 segue 为 indexPathForSelectedRow 返回 nil?