对于我的应用程序,创建可用作背景颜色的图案UIColor 更有帮助且性能更高。
一旦我将它添加为UIColor 的扩展,我就可以轻松地将它放在我的代码中的任何位置,它总是能完美地填充,即使视图旋转、缩小和增长!
你可以这样使用它:
view.backgroundColor = UIColor.red.patternStripes()
view.backgroundColor = UIColor.red.patternStripes(color2: .darkGray)
view.backgroundColor = UIColor.red.patternStripes(color2: .darkGray, barThickness: 25.0)
并获得这种美丽:
这是 UIColor 的扩展:
extension UIColor {
/// make a diagonal striped pattern
func patternStripes(color2: UIColor = .white, barThickness t: CGFloat = 25.0) -> UIColor {
let dim: CGFloat = t * 2.0 * sqrt(2.0)
let img = UIGraphicsImageRenderer(size: .init(width: dim, height: dim)).image { context in
// rotate the context and shift up
context.cgContext.rotate(by: CGFloat.pi / 4.0)
context.cgContext.translateBy(x: 0.0, y: -2.0 * t)
let bars: [(UIColor,UIBezierPath)] = [
(self, UIBezierPath(rect: .init(x: 0.0, y: 0.0, width: dim * 2.0, height: t))),
(color2,UIBezierPath(rect: .init(x: 0.0, y: t, width: dim * 2.0, height: t)))
]
bars.forEach { $0.0.setFill(); $0.1.fill() }
// move down and paint again
context.cgContext.translateBy(x: 0.0, y: 2.0 * t)
bars.forEach { $0.0.setFill(); $0.1.fill() }
}
return UIColor(patternImage: img)
}
}
基本上,我正在为一个要绘制的小矩形创建一个临时绘图空间。我用一种图案来绘制它,这种图案在重复时会在各个方面无缝匹配。然后我拍下这张照片并告诉UIColor 将其用作图案。
我必须使图案图像足够大以将每个条形绘制两次的技巧。结果是条形厚度 * 2 * sqrt(2)。
我知道我可能会因为风格而受到抨击。以下是我的想法:
- 我使用了像
t 这样的一个字母变量,它的描述性不是很好。我的辩护:我认为它使方程式更具可读性,并且当它仅限于接下来的几行时感觉还可以。
- 元组。与 #1 相同
- 使用小数(
4.0 而不仅仅是4)。我宁愿不使用小数,但我发现使用小数的编译时间更好。在更大的项目中,它可以产生巨大的影响。我还要承认,它读起来可能不漂亮,但减少类型的歧义甚至对人类也有帮助。
3 种颜色:
我刚刚意识到最初的问题是要求 3 种颜色,所以这里有一个版本......
首先,数学:
更新代码:
extension UIColor {
/// make a diagonal striped pattern
func pattern3Stripes(color2: UIColor, color3: UIColor, barThickness t: CGFloat = 25.0) -> UIColor {
let sqrt2: CGFloat = sqrt(2.0)
let dim: CGFloat = t * 3.0 * sqrt2
let size: CGSize = .init(width: dim, height: dim)
let img = UIGraphicsImageRenderer(size: size).image { context in
// rotate the context and shift up
context.cgContext.rotate(by: CGFloat.pi / 4.0)
context.cgContext.translateBy(x: 0.0, y: -3.0 * t)
let bars: [(UIColor,UIBezierPath)] = [
(self, UIBezierPath(rect: .init(x: 0.0, y: 0.0, width: dim * sqrt2, height: t))),
(color2,UIBezierPath(rect: .init(x: 0.0, y: t, width: dim * sqrt2, height: t))),
(color3,UIBezierPath(rect: .init(x: 0.0, y: 2.0 * t, width: dim * sqrt2, height: t)))
]
bars.forEach { $0.0.setFill(); $0.1.fill() }
// move down and paint again
context.cgContext.translateBy(x: 0.0, y: 3.0 * t)
bars.forEach { $0.0.setFill(); $0.1.fill() }
}
return UIColor(patternImage: img)
}
}
用法:
view.backgroundColor = UIColor.green.pattern3Stripes(color2: .white, color3: .red, barThickness: 25.0)
结果: