简体   繁体   中英

Swift / cut background image

My background image is set with UIView extension.

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. 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.

Help is very appreciated.

You can use .ScaleAspectFill to crop the image rather than scale it to fit. 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

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)
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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