[英]Adding a gradient layer on top of a UIButton's backgroundImage
我有一個項目,UIStackView中有一些按鈕。 每個按鈕都有一個backgroundImage。 一切都按需渲染,但是我想在backgroundImage前面放置一個半透明的漸變層,以便按鈕上的文本具有更多的對比度。
我試圖在viewDidLoad
使用此代碼在每個UIButton的backgroundImage前面添加一個半透明的漸變:
buttonArray = [buttonOne, buttonTwo, buttonThree, buttonFour]
let gradientLayer = CAGradientLayer()
gradientLayer.colors = [UIColor(white: 1.0, alpha: 0.5)]
// gradientLayer.colors = [UIColor(white: 1.0, alpha: 0.5).cgColor]
// gradientLayer.colors = [UIColor.orange]
// gradientLayer.colors = [UIColor.orange.cgColor]
buttonArray.forEach({$0.imageView?.layer.insertSublayer(gradientLayer, at: 0)})
就目前而言,什么也沒有添加。 我嘗試將顏色更改為沒有alpha值的顏色,然后將所需的顏色更改為.cgColor。 沒有骰子。 感謝您的閱讀。 我歡迎您提出有關如何在UIButton的backgroundImage前面放置gradientLayer的建議。
我基於此處找到的代碼進行嘗試
我認為您必須指定一種以上的顏色以及該圖層的邊界:
let buttonArray = [buttonOne, buttonTwo, buttonThree, buttonFour]
for button in buttonArray {
let gradientLayer = CAGradientLayer()
gradientLayer.colors = [UIColor(white: 0.5, alpha: 0.5).cgColor, UIColor(white: 1.0, alpha: 0.5).cgColor]
gradientLayer.frame = (button?.bounds)!
button?.layer.insertSublayer(gradientLayer, at: 0)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.