简体   繁体   中英

UIImage in a Rounded UIView swift

I created a UIView and inthe UIView, I added an Imageview. I gave the UIView corner radius and it works, the propble I have now is that the image that I place inside does not respect the cornerradius of the view and as a result, it shows the entire image as a rectangle instead of having the topleft and topRight corner curved to the same radius of the UIView. my code is shown below.

let bgView: UIView = {
        let bgView = UIView()
        bgView.backgroundColor = .white
        return bgView
    }()

    let propertyImage: DefaultImageView = {
        let img = DefaultImageView(frame: .zero)
        img.clipsToBounds = true
        img.layer.masksToBounds = true
        img.image = #imageLiteral(resourceName: "icons8-name-filled-30")
        img.contentMode = .scaleToFill
        return img
    }()

this gives the rounded cardview

extension UIView {
func addShadowAndRoundCorners() {
        layer.shadowOpacity = 1
        layer.shadowOffset = CGSize.zero
        layer.shadowColor = UIColor.darkGray.cgColor
        layer.cornerRadius = 12
    }
 }

so I added the rounded style like bgView.addShadowAndRoundCorners

How can I make the imageview stay withing the rounded corners of the UIView

The clipsToBounds to yes needs to be added to the container view as well in order to force the subviews not to render outside:

bgView.clipsToBounds = true

Or you can just round the imageView itself.

If you only want the topLeft and topRight corners of the UIImageView rounded, you will probably have to use masking before displaying the image.

Create a CGContext the same size as the image, create the mask in the CGContext, then draw the image into the context, the mask will be applied, then get the new image from the context and put it in .image of the UIImageView.

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