我想绘制一个UIView图层,但是当我这样做时,图层框架不等于(在预览中)UIView框架。
class ViewController: UIViewController {
var graphHeight:CGFloat = 100
var graphSize:CGFloat!
override func viewDidLoad() {
super.viewDidLoad()
graphSize = self.view.frame.height/CGFloat(M_PI)
let graphRect:CGRect = CGRectMake(0, graphHeight, self.view.frame.width, graphSize)
let background = blueGardient()
var theView:UIView = UIView(frame: graphRect)
background.frame = theView.frame
theView.backgroundColor = UIColor.yellowColor()
theView.layer.cornerRadius = 8
theView.layer.borderWidth = 1
theView.layer.borderColor = UIColor.redColor().CGColor
theView.layer.insertSublayer(background, atIndex: 0)
self.view.addSubview(theView)
}
func blueGardient()->CAGradientLayer{
let topColor = UIColor(red: 0, green: 0, blue: 255, alpha: 0.7)
let bottomColor = UIColor(red: 0, green: 0, blue: 255, alpha: 0.9)
let gradientColors: [CGColor] = [topColor.CGColor, bottomColor.CGColor]
let gradientLocations: [Float] = [0.0, 1.0]
let gradientLayer: CAGradientLayer = CAGradientLayer()
gradientLayer.colors = gradientColors
gradientLayer.locations = gradientLocations
return gradientLayer
}
}
框架相等
(0.0,100.0,320.0,180.800015352393)
(0.0,100.0,320.0,180.800015352393)
但未显示eauql。我尝试使用theView.layer.frame但未成功...
最佳答案
问题是因为每个帧的上下文不同。您的 View 框架(theView.frame
)在其 super View 的上下文中,因此(0,100)的原点意味着它从屏幕左上角向下偏移100点。图层的框架(background.frame
)在其所属 View (theView
)的上下文中,因此相同的(0,100)原点意味着蓝色图层从 View 的左上角偏移100个点。
代替使用 View 的frame
,而是使用 View 的bounds
的大小和(0,0)原点创建一个新的rect:
background.frame = CGRect(origin: CGPointZero, size: theView.bounds.size)