坚持用虚线创建圆形视图,但有多种颜色
Posted
技术标签:
【中文标题】坚持用虚线创建圆形视图,但有多种颜色【英文标题】:Stuck in creating a rounded view with dashed lines but with multiple colors 【发布时间】:2021-06-21 12:30:13 【问题描述】:我想在我的应用程序中创建这种设计(已添加图片)。我已经尝试使用复制器层创建它,但是如何管理这种模式中的不同颜色?
let replicatorLayer = CAReplicatorLayer()
replicatorLayer.frame.size = viewForReplicatorLayer.frame.size
replicatorLayer.masksToBounds = true
replicatorLayer.instanceColor = UIColor.red.cgColor
let radius = viewForReplicatorLayer.frame.size.width/2 - 30
let circum = 2 * CGFloat.pi * radius
let num = circum/10 + 21
let instanceCount = num//100//viewForReplicatorLayer.frame.width / image!.size.width
replicatorLayer.instanceCount = Int(instanceCount)//Int(ceil(instanceCount))
replicatorLayer.instanceDelay = 1.0
viewForReplicatorLayer.layer.addSublayer(replicatorLayer)
let layer = CALayer()
let x = viewForReplicatorLayer.bounds.midX
layer.frame = CGRect(x: x, y: 0, width: 3, height: 10)
layer.backgroundColor = UIColor.red.cgColor
replicatorLayer.addSublayer(layer)
let angle = Float.pi * 2 / Float(instanceCount)
replicatorLayer.instanceTransform = CATransform3DMakeRotation(CGFloat(angle), 0, 0, 1)
这就是我想做的:
【问题讨论】:
【参考方案1】:我会用你想要的颜色创建一个圆锥渐变层,然后使用复制器层来掩盖这个渐变层。
创建具有所需颜色的渐变层:
let orangeColor = UIColor(red: 236.0 / 255.0, green: 184.0 / 255.0, blue: 63.0 / 255.0, alpha: 1.0)
let purpleColor = UIColor(red: 172.0 / 255.0, green: 56.0 / 255.0, blue: 213.0 / 255.0, alpha: 1.0)
let gradientLayer = CAGradientLayer()
gradientLayer.frame = viewForReplicatorLayer.bounds
gradientLayer.type = .conic
gradientLayer.colors = [
orangeColor.cgColor,
purpleColor.cgColor,
purpleColor.withAlphaComponent(0).cgColor
]
let center = CGPoint(x: 0.5, y: 0.5)
gradientLayer.startPoint = center
gradientLayer.endPoint = CGPoint(x: 0.5, y: 0)
viewForReplicatorLayer.layer.addSublayer(gradientLayer)
将复制层设置为渐变层的遮罩:
gradientLayer.mask = replicatorLayer
由于我们使用复制器层作为遮罩,因此无需再将其添加为子层,因此请从现有代码中删除以下内容:
viewForReplicatorLayer.layer.addSublayer(replicatorLayer)
【讨论】:
【参考方案2】:从橙色开始,橙色是 RGB (1; 0.5; 0),然后是紫色,紫色是 RGB (1; 0; 1)。
R: 1 -> 1
G: 0.5 -> 0
B: 0 -> 1
所以,我们只需要复制它:
replicatorLayer.instanceBlueOffset = 1 / Float(instanceCount)
replicatorLayer.instanceGreenOffset = -(1.0 / Float(instanceCount * 2)) //There is the 2 factor because because this color speed is twice less the blue one
其他一些变化:
replicatorLayer.instanceColor = UIColor(red: 1, green: 0.5, blue: 0, alpha: 1).cgColor
...
layer.backgroundColor = UIColor.white.cgColor
【讨论】:
instanceBlueOffset和greenoffset如何计算? 参见“B:从 0 到 1”和 G 到“0.5 到 0”。然后将值除以步数?以上是关于坚持用虚线创建圆形视图,但有多种颜色的主要内容,如果未能解决你的问题,请参考以下文章