如何在swift中创建虚线?

gt0wga4j  于 12个月前  发布在  Swift
关注(0)|答案(8)|浏览(114)

我想知道如何在swift中创建一条虚线,就像这样:-而不是像这样的常规直线:--,我知道我可以创建多行,但如果我只能用一行来写,那将需要很多不必要的代码。

plupiseo

plupiseo1#

  • 斯威夫特4号酒店,纽约**
@IBOutlet var dashedView: UIView!

func drawDottedLine(start p0: CGPoint, end p1: CGPoint, view: UIView) {
    let shapeLayer = CAShapeLayer()
    shapeLayer.strokeColor = UIColor.lightGray.cgColor
    shapeLayer.lineWidth = 1
    shapeLayer.lineDashPattern = [7, 3] // 7 is the length of dash, 3 is length of the gap.

    let path = CGMutablePath()
    path.addLines(between: [p0, p1])
    shapeLayer.path = path
    view.layer.addSublayer(shapeLayer)
}

字符串

调用函数

drawDottedLine(start: CGPoint(x: dashedView.bounds.minX, y: dashedView.bounds.minY), end: CGPoint(x: dashedView.bounds.maxX, y: dashedView.bounds.minY), view: dashedView)


有了上面的你将有一条直线,你也可以改变点,因为你想,例如,如果你改变端点的y从dashedView.bounds.minYdashedView.bounds.maxY,你将有对角线。
如果你将在UIView的子类中使用它,你将没有出口,所以你将使用它与self代替。

stszievb

stszievb2#

创建虚线的方法与使用Swift的方法相同,不同的是使用Swift。
以下是使用UIBezierPath的方法:

let  path = UIBezierPath()

let  p0 = CGPoint(x: self.bounds.minX, y: self.bounds.midY)
path.move(to: p0)

let  p1 = CGPoint(x: self.bounds.maxX, y: self.bounds.midY)
path.addLine(to: 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.magenta.set()
path.stroke()

字符串
以下是如何使用UIBezierPath绘制虚线:

let  path = UIBezierPath()

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

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

let  dashes: [ CGFloat ] = [ 0.0, 16.0 ]
path.setLineDash(dashes, count: dashes.count, phase: 0.0)
path.lineWidth = 8.0
path.lineCapStyle = .Round
UIColor.magentaColor().set()
path.stroke()


以下是如何使用CGContext绘制虚线:

let  context: CGContext = UIGraphicsGetCurrentContext()!

let  p0 = CGPointMake(CGRectGetMinX(self.bounds), CGRectGetMidY(self.bounds))
CGContextMoveToPoint(context, p0.x, p0.y)

let  p1 = CGPointMake(CGRectGetMaxX(self.bounds), CGRectGetMidY(self.bounds))
CGContextAddLineToPoint(context, p1.x, p1.y)

let  dashes: [ CGFloat ] = [ 16.0, 32.0 ]
CGContextSetLineDash(context, 0.0, dashes, dashes.count)

CGContextSetLineWidth(context, 8.0)
CGContextSetLineCap(context, .Butt)
UIColor.blueColor().set()
CGContextStrokePath(context)

xwbd5t1u

xwbd5t1u3#

通过使用继承自UIView的自定义类,也支持故事板。

你所需要做的就是在故事板中创建一个视图,为这个视图分配类,然后看看故事板中的魔力。

@IBDesignable
class DashedLineView : UIView {
    @IBInspectable var perDashLength: CGFloat = 2.0
    @IBInspectable var spaceBetweenDash: CGFloat = 2.0
    @IBInspectable var dashColor: UIColor = UIColor.lightGray

    override func draw(_ rect: CGRect) {
        super.draw(rect)
        let  path = UIBezierPath()
        if height > width {
            let  p0 = CGPoint(x: self.bounds.midX, y: self.bounds.minY)
            path.move(to: p0)

            let  p1 = CGPoint(x: self.bounds.midX, y: self.bounds.maxY)
            path.addLine(to: p1)
            path.lineWidth = width

        } else {
            let  p0 = CGPoint(x: self.bounds.minX, y: self.bounds.midY)
            path.move(to: p0)

            let  p1 = CGPoint(x: self.bounds.maxX, y: self.bounds.midY)
            path.addLine(to: p1)
            path.lineWidth = height
        }

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

        path.lineCapStyle = .butt
        dashColor.set()
        path.stroke()
    }

    private var width : CGFloat {
        return self.bounds.width
    }

    private var height : CGFloat {
        return self.bounds.height
    }
}

字符串

fbcarpbf

fbcarpbf4#

这里有一个易于使用的UIView,它画了一条虚线。
我接受了@Fan Jin的回答,并创建了一个UIView子类,它应该可以很好地与Auto Layout一起工作。

Swift 5.3,Xcode 12

import UIKit

public class DashedView: UIView {

    public struct Configuration {
        public var color: UIColor
        public var dashLength: CGFloat
        public var dashGap: CGFloat

        public init(
            color: UIColor,
            dashLength: CGFloat,
            dashGap: CGFloat) {
            self.color = color
            self.dashLength = dashLength
            self.dashGap = dashGap
        }

        static let `default`: Self = .init(
            color: .lightGray,
            dashLength: 7,
            dashGap: 3)
    }

    // MARK: - Properties

    /// Override to customize height
    public class var lineHeight: CGFloat { 1.0 }

    override public var intrinsicContentSize: CGSize {
        CGSize(width: UIView.noIntrinsicMetric, height: Self.lineHeight)
    }

    public final var config: Configuration = .default {
        didSet {
            drawDottedLine()
        }
    }

    private var dashedLayer: CAShapeLayer?

    // MARK: - Life Cycle

    override public func layoutSubviews() {
        super.layoutSubviews()

        // We only redraw the dashes if the width has changed.
        guard bounds.width != dashedLayer?.frame.width else { return }

        drawDottedLine()
    }

    // MARK: - Drawing

    private func drawDottedLine() {
        if dashedLayer != nil {
            dashedLayer?.removeFromSuperlayer()
        }

        dashedLayer = drawDottedLine(
            start: bounds.origin,
            end: CGPoint(x: bounds.width, y: bounds.origin.y),
            config: config)
    }

}

// Thanks to: https://stackoverflow.com/a/49305154/4802021
private extension DashedView {
    func drawDottedLine(
        start: CGPoint,
        end: CGPoint,
        config: Configuration) -> CAShapeLayer {
        let shapeLayer = CAShapeLayer()
        shapeLayer.strokeColor = config.color.cgColor
        shapeLayer.lineWidth = Self.lineHeight
        shapeLayer.lineDashPattern = [config.dashLength as NSNumber, config.dashGap as NSNumber]

        let path = CGMutablePath()
        path.addLines(between: [start, end])
        shapeLayer.path = path
        layer.addSublayer(shapeLayer)

        return shapeLayer
    }
}

字符串

hwazgwia

hwazgwia5#

我的扩展方法是从@FanJins的答案构建的

extension UIView {

    func createDashedLine(from point1: CGPoint, to point2: CGPoint, color: UIColor, strokeLength: NSNumber, gapLength: NSNumber, width: CGFloat) {
        let shapeLayer = CAShapeLayer()

        shapeLayer.strokeColor = color.cgColor
        shapeLayer.lineWidth = width
        shapeLayer.lineDashPattern = [strokeLength, gapLength]

        let path = CGMutablePath()
        path.addLines(between: [point1, point2])
        shapeLayer.path = path
        layer.addSublayer(shapeLayer)
    }
}

字符串
然后调用方法看起来像这样:

let topPoint = CGPoint(x: view.frame.midX, y: view.bounds.minY)
let bottomPoint = CGPoint(x: view.frame.midX, y: view.bounds.maxY)

view.createDashedLine(from: topPoint, to: bottomPoint, color: .black, strokeLength: 4, gapLength: 6, width: 2)

i34xakig

i34xakig6#

非常简单的SWIFT 4.2UIView扩展:

extension UIView {
    private static let lineDashPattern: [NSNumber] = [2, 2]
    private static let lineDashWidth: CGFloat = 1.0

    func makeDashedBorderLine() {
        let path = CGMutablePath()
        let shapeLayer = CAShapeLayer()
        shapeLayer.lineWidth = UIView.lineDashWidth
        shapeLayer.strokeColor = UIColor.lightGray.cgColor
        shapeLayer.lineDashPattern = UIView.lineDashPattern
        path.addLines(between: [CGPoint(x: bounds.minX, y: bounds.height/2),
                                CGPoint(x: bounds.maxX, y: bounds.height/2)])
        shapeLayer.path = path
        layer.addSublayer(shapeLayer)
    }
}

字符串

4c8rllxm

4c8rllxm7#

目标C**

  • @user3230875* 的回答帮助我理解了画虚线需要什么。

所以我希望这个答案可以帮助Obj-C搜索者

//dashed line
    path = [UIBezierPath bezierPath];
    [path moveToPoint:CGPointMake(dashedLineStartX, dashedLineStartY)];
    [path addLineToPoint:CGPointMake(dashedLineEndX, dashedLineEndY)];
    path.lineWidth = 5;
    [color setStroke];
    CGFloat dashes[] = {4.0,8.0};
    [path setLineDash:dashes count:2 phase:0.0];
    path.lineCapStyle = kCGLineCapButt;
    [path stroke];

字符串

ecfsfe2w

ecfsfe2w8#

@clément-cardonnel的回答的修改版本。
通过isVertical选项和IBInspectable属性增强

class DottedLineView : UIView {
        @IBInspectable var perDashLength: CGFloat = 2.0
        @IBInspectable var spaceBetweenDash: CGFloat = 2.0
        @IBInspectable var dashColor: UIColor = UIColor.gray
        @IBInspectable var lineWidth: CGFloat = 2.0
        @IBInspectable var isVertical: Bool = false
        
    private var dashedLayer: CAShapeLayer?
    
    override public func layoutSubviews() {
        super.layoutSubviews()
        
        guard bounds.width != dashedLayer?.frame.width,
              bounds.height != dashedLayer?.frame.height
        else { return }
        
        drawDottedLine()
    }
    
    private func drawDottedLine() {
        if dashedLayer != nil {
            dashedLayer?.removeFromSuperlayer()
        }
        
        var startPoint = CGPoint(
            x: bounds.width / 2 + lineWidth / 2,
            y: 0
        )
        var endPoint = CGPoint(
            x: bounds.width / 2 + lineWidth / 2,
            y: bounds.height
        )
        
        if !isVertical {
            startPoint = CGPoint(
                x: 0,
                y: bounds.height / 2 + lineWidth / 2
            )
            endPoint = CGPoint(
                x: bounds.width,
                y: bounds.height / 2 + lineWidth / 2
            )
        }
        
        dashedLayer = drawDottedLine(
            startPoint: startPoint,
            endPoint: endPoint
        )
    }
    
    private func drawDottedLine(startPoint: CGPoint, endPoint: CGPoint) -> CAShapeLayer {
        let shapeLayer = CAShapeLayer()
        shapeLayer.strokeColor = dashColor.cgColor
        shapeLayer.lineWidth = self.lineWidth
        shapeLayer.lineDashPattern = [perDashLength as NSNumber, spaceBetweenDash as NSNumber]
        
        let path = CGMutablePath()
        path.addLines(between: [startPoint, endPoint])
        shapeLayer.path = path
        layer.addSublayer(shapeLayer)
        
        return shapeLayer
    }
}

字符串

相关问题