To maximize and display the UIImageView image from above while maintaining aspect

Asked 2 years ago, Updated 2 years ago, 80 views

I am using Xcode 9.4.1 (Swift 4.1).
The UIImageView displays the image, but the content mode is set to Aspect Fill from the storyboard, and first maximize it to the full UIImageView.Also, I don't want the top and bottom protruding parts to be displayed, so check Clip to Bounds.

However, the image is in the upper and lower center.The image below doesn't have to be completely visible, so I would like to arrange it so that I can see the top of the image.

How should I specify it?
Please let me know if you know.

swift uiimageview

2022-09-29 22:56

1 Answers

I'm sorry it's a utility method, but you can do it if you insert a code that cuts out the image you want to set in the UIImageView as follows:

Clip and set the image specified in //image to fit in toSetImgView
/// -parameter image:image you want to set in UIImageView
/// -parameter toSetImgView—Instance of UIImageView where you want to set the image
funcsetReservedImageToUIImageView (image: UIImage, toSetImgView: UIImageView)
{
    letcImg: CGIimage?=image.cgImage;
    if(cImg==nil)
    {
        return
    }

    // Cut out the image so that it can be displayed well
    let imgRef:CGImage?=cImg?.cropping(to:CGRect(x:0,y:0,width:image.size.width,height:toSetImgView.frame.size.height*image.size.width/toSetImgView.frame.size.width))
    if(imgRef==nil)
    {
        return
    }

    let newImg=UIImage(cgImage:imgRef!, scale:image.scale, orientation:image.imageOrientation)

    toSetImgView.image=newImg
}

Actually, I wanted to inherit UIImageView and do it on KVO, but Swift was unfamiliar and didn't work.(I think it's a poor code for Swift.)
If you receive notification that the image property has been changed in KVO, you will be able to make it smarter by calling the above process there.


2022-09-29 22:56

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.