[英]How to create an Eraser for CALayer.SubLayer Using a CAShapeLayer in Swift
[英]How to get the fillColor of a sublayer in Swift?
我在各個 UIView 中創建了許多圓圈。 圓圈由 CAShapeLayer 制成,具有不同的 colors。
每個 UIView 都保存在一個數組中。
當我在數組中選擇一個隨機索引時,我想用該索引“測量”圓的顏色。
我試圖訪問 UIView 的子層,然后獲取它的“背景顏色”。 但我得到一個零值。
func createBalls(addToView circleView: UIView, x: CGFloat, y: CGFloat, size: CGFloat, color: CGColor) -> UIView {
//create view to contain circle
let containerView: UIView = {
let view = UIView()
view.backgroundColor = .clear
return view
}()
// add container view to view
containerView.frame = CGRect(x: x + size/2, y: y + size/2, width: size, height: size)
circleView.addSubview(containerView)
//create circle inside container view
let path = UIBezierPath(ovalIn: containerView.bounds)
let shapeLayer = CAShapeLayer()
shapeLayer.path = path.cgPath
shapeLayer.fillColor = color
shapeLayer.lineWidth = 3
shapeLayer.strokeColor = UIColor.black.cgColor
containerView.layer.addSublayer(shapeLayer)
circleView.clipsToBounds = false
return containerView
}
func sampleOfCircles(addToView circleView: UIView, circleSize: CGFloat) {
nBalls = Int.random(in: 3...5)
nRedBalls = Int.random(in: 1...nBalls - 1)
nBlueBalls = nBalls - nRedBalls
for i in 0...nBalls-1 {
let x = CGFloat(10 + i*(Int(circleSize) + 5))
let y = circleView.frame.height/2
if i < nRedBalls {
ballArray.append(createBalls(addToView: circleView, x: x, y: y, size: circleSize, color: UIColor.red.cgColor))
} else {
ballArray.append(createBalls(addToView: circleView, x: x, y: y, size: circleSize, color: UIColor.blue.cgColor))
}
}
}
func createBallProblem(viewStackLeft: UIView, viewStackRight: UIView, viewBottom: UIView) {
sampleOfCircles(addToView: viewStackLeft, circleSize: K.Ball.ballWidth)
for a in ballArray {
let color = a.layer.sublayers?.last?.backgroundColor
print(color)
}
}
您正在使用fillColor將顏色設置為圖層,而不是backgroundColor 。 這就是你收到nil的原因。
要檢索您設置的顏色,請使用以下代碼:
let color = (a.layer.sublayers?.last as? CAShapeLayer)?.fillColor
print(color)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.