简体   繁体   English

圆形的UIView swift中的UIImage

[英]UIImage in a Rounded UIView swift

I created a UIView and inthe UIView, I added an Imageview. 我创建了一个UIView,并在UIView中添加了一个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. 我给了UIView角半径,它可以工作,现在的问题是放置在其中的图像不考虑视图的角半径,因此,它将整个图像显示为矩形,而不是具有左上角和topRight角弯曲到与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 所以我添加了bgView.addShadowAndRoundCorners类的圆形样式

How can I make the imageview stay withing the rounded corners of the UIView 如何使imageview与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: 将clipsToBounds设置为yes时,也需要将其添加到容器视图中,以强制子视图不呈现在外部:

bgView.clipsToBounds = true

Or you can just round the imageView itself. 或者,您可以只对imageView本身进行四舍五入。

If you only want the topLeft and topRight corners of the UIImageView rounded, you will probably have to use masking before displaying the image. 如果只希望对UIImageView的topLeft和topRight角进行四舍五入,则可能必须在显示图像之前使用遮罩。

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. 创建一个与图像大小相同的CGContext,在CGContext中创建遮罩,然后将图像绘制到上下文中,将应用遮罩,然后从上下文中获取新图像并将其放入UIImageView的.image中。

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

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