Swift:渐变在旋转时分裂 [英] Swift: Gradient splits on rotation
问题描述
简而言之,我的渐变是深蓝色和黑色的混合.渐变看起来很漂亮,但是当我旋转屏幕并将其置于横向时,两种颜色会分开,并且屏幕的一半为蓝色背景,另一半为黑色.弄清楚我做得不好,我从这两个来源复制了代码:
In short, I have a gradient that is a mix of Dark Blue and Black. The gradient looks beautiful, however when I rotate the screen and put it in landscape, the two colors split and half of the screen has a blue background and the other half is black. Figuring I didn't do it right, I copied codes from these two sources:
YouTube视频 https://www.youtube.com/watch?v=pabNgxzEaRk
YouTube video https://www.youtube.com/watch?v=pabNgxzEaRk
网站 http://blog.apoorvmote.com/gradient-background- uiview-ios-swift/
这是我的代码:
let topColor = UIColor(red: 28/255.0, green: 25/255.0, blue: 127/255.0, alpha: 1)
let bottomColor = UIColor(red: 0/255.0, green: 0/255.0, blue: 25/255.0, alpha: 1)
let gradientColors: [CGColor] = [topColor.CGColor, bottomColor.CGColor]
let gradientLocations: [Float] = [0.0, 1.0]
let gradientLayer: CAGradientLayer = CAGradientLayer()
gradientLayer.colors = gradientColors
gradientLayer.locations = gradientLocations
gradientLayer.frame = self.view.bounds
self.view.layer.insertSublayer(gradientLayer, atIndex: 0)
有人可以将我指向正确的方向,以阻止我的梯度分裂为两部分吗?
Can someone point me in the right direction to stop my gradient from splitting in two?
推荐答案
请记住,更改屏幕方向时,所有视图的边界也会发生变化(假设您使用的是自动布局),但是同一问题不会应用于以编程方式添加的图层.因此,在您的情况下,渐变层仍然具有根据旋转之前的旧视图范围设置的框架.为了解决这个问题,我建议您对渐变视图进行子类化,并在每次视图边界更改时调用的layoutSubviews
函数中更新渐变图层框架.
Keep in mind that when changing screen orientation all view's bounds change as well (assuming you are using auto layout) but the same thing is not applied on programmatically added layers. So in your case gradient layer still has the frame which is set based on old view bounds before rotation. To solve this I suggest subclassing your gradient view and update gradient layer frame in layoutSubviews
function which is called on each view bounds change.
class GradientView: UIView {
let gradientLayer = CAGradientLayer()
override func awakeFromNib() {
gradientLayer.frame = self.bounds
gradientLayer.colors = yourColors
gradientLayer.locations = yourLocations
self.layer.addSublayer(gradientLayer)
}
override func layoutSubviews() {
gradientLayer.frame = self.bounds
}
}
这篇关于Swift:渐变在旋转时分裂的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!