绘制虚线(不是虚线!)线,2017 年使用 IBDesignable [英] Draw dotted (not dashed!) line, with IBDesignable in 2017

查看:20
本文介绍了绘制虚线(不是虚线!)线,2017 年使用 IBDesignable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 UIKit 绘制虚线很容易.所以:

It's easy to draw a dashed line with UIKit. So:

CGFloat dashes[] = {4, 2};
[path setLineDash:dashes count:2 phase:0];
[path stroke];

有没有办法画出真正的虚线?

Is there any way way to draw a genuine dotted line?

推荐答案

将线帽样式设置为圆形并将开启"长度设置为一个很小的数字.

Set the line cap style to round and set the "on" length to a tiny number.

Swift 游乐场示例:

Swift playground example:

import UIKit
import PlaygroundSupport

let path = UIBezierPath()
path.move(to: CGPoint(x:10,y:10))
path.addLine(to: CGPoint(x:290,y:10))
path.lineWidth = 8

let dashes: [CGFloat] = [0.001, path.lineWidth * 2]
path.setLineDash(dashes, count: dashes.count, phase: 0)
path.lineCapStyle = CGLineCap.round

UIGraphicsBeginImageContextWithOptions(CGSize(width:300, height:20), false, 2)

UIColor.white.setFill()
UIGraphicsGetCurrentContext()!.fill(.infinite)

UIColor.black.setStroke()
path.stroke()

let image = UIGraphicsGetImageFromCurrentImageContext()
let view = UIImageView(image: image)
PlaygroundPage.current.liveView = view

UIGraphicsEndImageContext()

结果:

对于objective-C,使用与问题中相同的示例类,只需添加

For objective-C, using the same example class as in the question, simply add

CGContextSetLineCap(cx, kCGLineCapRound);

在调用 CGContextStrokePath 之前,更改 ra 数组值以匹配我的 Swift 代码.

before the call to CGContextStrokePath, and change the ra array values to match my Swift code.

这篇关于绘制虚线(不是虚线!)线,2017 年使用 IBDesignable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆