gpt4 book ai didi

swift - 在 swift 中绘制虚线背景

转载 作者:行者123 更新时间:2023-11-28 05:45:02 30 4
gpt4 key购买 nike

我正在尝试实现可以​​用作背景的虚线 View 。看起来有点像这样: Image showing dotted background

但我的代码似乎遗漏了一些东西。我尝试用不同大小的点和所有东西进行实验,但到目前为止,我只是将我的背景颜色设置为 View ,但无论大小、颜色或间距如何,都没有点。我错过了什么?

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

最佳答案

你有一个错误。只需将第二行更改为 UIColor.white.setFill() 并在 drawPattern 中将颜色更改为黑色:context.setFillColor(UIColor.black.cgColor)

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

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

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

关于swift - 在 swift 中绘制虚线背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55097530/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com