为 UIImageView 在 Draw 中设置圆角半径

Posted

技术标签:

【中文标题】为 UIImageView 在 Draw 中设置圆角半径【英文标题】:Setting Corner Radius in Draw for UIImageView 【发布时间】:2017-03-03 20:25:22 【问题描述】:

我在 UIImageView 的 draw 方法中设置了一些属性。但是,这些似乎根本没有受到任何影响。我看不到圆角,也没有遮蔽效果。视图如下:

//
//  RoundImage.swift
//
//

import UIKit

class RoundImage: UIImageView 

    //------------------
    //MARK: - Setup and Initialization
    //------------------

    override init(frame: CGRect) 
        super.init(frame: frame)

        self.initialize()
    

    required init?(coder aDecoder: NSCoder) 
        super.init(coder: aDecoder)

        self.initialize()
    

    override func draw(_ rect: CGRect) 
        super.draw(rect)

        self.layer.cornerRadius = 30
        self.layer.masksToBounds = true
        self.clipsToBounds = true
    

    //Setups content, styles, and defaults for the view
    private func initialize()
        self.initStyle()
    

    //Sets static content for the view
    private func staticContent() 

    

    //Styles the view's colors, borders, etc at initialization
    private func initStyle()


    

    //Styles the view for variables that must be set at runtime
    private func runtimeStyle()

        //TODO: These values cannot be changed in interface builder, but they should be able to be

    

    //------------------
    //MARK: - Interface Builder Methods
    //------------------

    //Sets the view up for interface builder with runtime styling and temp display values
    override func prepareForInterfaceBuilder() 
        self.runtimeStyle()
        self.staticContent()
    

    //------------------
    //MARK: - Lifecycle Methods
    //------------------

    //Sets the view up with runtime styling and values
    override func awakeFromNib() 
        super.awakeFromNib()

        self.runtimeStyle()
            self.staticContent()
        


    

【问题讨论】:

问这个问题可能有点傻,但是如果您在情节提要中将其用于 UIImageView,您是否确定设置了类?如果您已经这样做了,请在 draw 函数中添加一个断点并检查它是否在那里中断。 @PratikPatel 是的,我设置了课程。奇怪的是,它根本没有在我的 draw 方法中达到我的断点。 【参考方案1】:

子类化时的 UIImageView 根本不调用 draw 方法。这是不允许的,尽管文档很少。在这种情况下,建议继承 UIView,然后自己在 draw 方法中在视图上绘制图像。

更多信息:

drawRect not being called in my subclass of UIImageView

【讨论】:

以上是关于为 UIImageView 在 Draw 中设置圆角半径的主要内容,如果未能解决你的问题,请参考以下文章

如何在构建 UIImageView 时创建图像

在 ios 中使用原始尺寸在 UIImageView 中设置图像

在表格视图单元格内的 UIImageView 中设置图像

如何在 scrollViewDidZoom 中动态调整 contentInset?我最初在 UIScrollview 中设置 UIImageView 的 contentInset

缩小放置在 UIScrollView 中的 UIImageView

单个 UIImageView 显示两个单独的图像