简体   繁体   English

迅速/剪切背景图片

[英]Swift / cut background image

My background image is set with UIView extension. 我的背景图片设置了UIView扩展。

extension UIView {
    func addBackground() {
        // screen width and height:
        let width = UIScreen.mainScreen().bounds.size.width
        let height = UIScreen.mainScreen().bounds.size.height

        let imageViewBackground = UIImageView(frame: CGRectMake(0, 0, width, height))
        imageViewBackground.image = UIImage(named: "index_clear")

        // you can change the content mode:
        imageViewBackground.contentMode = UIViewContentMode.ScaleAspectFill
        self.addSubview(imageViewBackground)
        self.sendSubviewToBack(imageViewBackground)
    }}

For segue animation the view moves from left to right. 对于segue动画,视图从左向右移动。 The background image is way larger than the screen, what is visible while the animation. 背景图像比屏幕大很多,动画时可见。

How can I cut the background image to perfectly fit into the view? 如何剪切背景图像以使其完全适合视图? .ScaleAspectFit does the job, but since it's a picture it looks bad. .ScaleAspectFit完成这项工作,但是由于它是一张图片,因此看起来很糟糕。

Help is very appreciated. 非常感谢您的帮助。

You can use .ScaleAspectFill to crop the image rather than scale it to fit. 您可以使用.ScaleAspectFill裁剪图像,而不是缩放以适合图像。 This won't distort your image, but obviously you won't be able to see the whole thing. 这不会扭曲您的图像,但是显然您将看不到整个东西。

You need to ensure that you set clipsToBounds=true on the UIImageView so that the cropped area isn't visible 您需要确保在UIImageView上设置clipsToBounds=true ,以使裁剪区域不可见

extension UIView {
    func addBackground() {
        // screen width and height:
        let width = UIScreen.mainScreen().bounds.size.width
        let height = UIScreen.mainScreen().bounds.size.height

        let imageViewBackground = UIImageView(frame: CGRectMake(0, 0, width, height))
        imageViewBackground.image = UIImage(named: "index_clear")

        // you can change the content mode:
        imageViewBackground.contentMode = UIViewContentMode.ScaleAspectFill
        imageViewBackground.clipsToBounds=true
        self.addSubview(imageViewBackground)
        self.sendSubviewToBack(imageViewBackground)
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM