【发布时间】:2019-05-06 05:09:38
【问题描述】:
我正在尝试在我的 ios 应用程序中的图像上放置灰色透明渐变,但由于框架问题,它不起作用。由于我的UIImageView 是通过编程方式设置并使用translatesAutoresizingMaskIntoConstraints = false 设置的,因此当我将其框架设置为图像框架时,渐变层是不可见的。我不想将任一帧设置为常量,因为图像位于集合视图单元格中,该单元格使用sizeForItemAt 函数来确定每个单元格的大小,因此图像的大小会随着单元格,我需要我的渐变具有与图像相同的大小。
我试图通过创建一个UIView 来设置渐变,我将其放置为UIImageView 的子视图,但由于框架再次出现问题而没有运气。我看过其他关于添加渐变层的帖子,但它们都要求我为渐变定义一个框架。
//This is the imageview and the gradient that I want to apply to it
let profileImageView: UIImageView = {
let imageView = UIImageView()
imageView.contentMode = .scaleAspectFill
imageView.translatesAutoresizingMaskIntoConstraints = false
return imageView
} ()
var gradient: CAGradientLayer = {
let gradientLayer = CAGradientLayer()
gradientLayer.colors = [UIColor.clear.cgColor, UIColor.gray.cgColor]
gradientLayer.opacity = 0.7
return gradientLayer
}()
//This is the setupviews() function where I apply the gradient to the imageview
func setupViews() {
self.contentView.addSubview(profileImageView)
profileImageView.layer.addSublayer(gradient)
//constraints for profileImageView
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[v0]-0-|", options: NSLayoutConstraint.FormatOptions(), metrics: nil, views: ["v0": profileImageView]))
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[v0]-0-|", options: NSLayoutConstraint.FormatOptions(), metrics: nil, views: ["v0": profileImageView]))
}
目前为了显示渐变,我需要在setupViews() 中为渐变层定义一个框架,但正如我之前所述,我不想这样做。有没有一种方法可以在不定义特定框架的情况下创建渐变层,或者在我的情况下是否有另一种更好的方法来应用渐变层?谢谢!
编辑:我想澄清一下,我的 UICollectionViewCell 类中的所有视图都没有框架。它们都以编程方式设置了约束,因此如果我尝试打印view.frame.height 或view.frame.width,尽管视图的实际高度和宽度不为零,但程序将打印为零。因此,为渐变定义任何类型的框架或将渐变的框架设置为视图的框架都不起作用。我是否必须重新构建视图的设置方式才能在图像上放置渐变?或者我还能希望从这个问题中得到救赎吗?谢谢!
【问题讨论】:
标签: ios swift xcode uiimageview gradient