在swift中绘制虚线背景

问题描述 投票:1回答:1

我试图实现我可以用作背景的虚线视图。看起来有点像这样的东西:Image showing dotted background

但我似乎在我的代码中遗漏了一些东西。我试图用不同大小的点和一切来实验,但到目前为止,我只是将背景颜色设置为视图,但无论大小,颜色或间距都没有点。我错过了什么?

class DottedBackgroundView: UIView {

override func draw(_ rect: CGRect) {
    guard let context = UIGraphicsGetCurrentContext() else { return }
    UIColor.green.setFill()
    context.fill(rect)

    let drawPattern: CGPatternDrawPatternCallback = { _, context in
        context.addArc(
            center: CGPoint(x: 5, y: 5), radius: 2.5,
            startAngle: 0, endAngle: CGFloat(2.0 * .pi),
            clockwise: false)
        context.setFillColor(UIColor.white.cgColor)
        context.fillPath()
    }

    var callbacks = CGPatternCallbacks(
        version: 0, drawPattern: drawPattern, releaseInfo: nil)

    let pattern = CGPattern(
        info: nil,
        bounds: CGRect(x: 0, y: 0, width: 10, height: 10),
        matrix: .identity,
        xStep: 10,
        yStep: 10,
        tiling: .constantSpacing,
        isColored: true,
        callbacks: &callbacks)

    let patternSpace = CGColorSpace(patternBaseSpace: nil)!
    context.setFillColorSpace(patternSpace)

    var alpha: CGFloat = 1.0
    context.setFillPattern(pattern!, colorComponents: &alpha)
    context.fill(rect)

    context.addArc(
        center: CGPoint(x: 5, y: 5), radius: 5.0,
        startAngle: 0, endAngle: CGFloat(2.0 * .pi),
        clockwise: false)
    }
}
swift core-graphics
1个回答
1
投票

你有一个bug。只需将第二行更改为UIColor.white.setFill(),然后将drawPattern更改为黑色:context.setFillColor(UIColor.black.cgColor)

有用。我在Storyboard上设置了这个视图,但如果你从代码中添加它,试试这个:

let dottedView = DottedBackgroundView()
dottedView.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(dottedView)

NSLayoutConstraint.activate([
    dottedView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor),
    dottedView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor),
    dottedView.topAnchor.constraint(equalTo: self.view.topAnchor),
    dottedView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor)
])

您需要设置约束,因为您的自定义视图没有定义的大小,因此无法正确调整大小。

© www.soinside.com 2019 - 2024. All rights reserved.