如何在Swift中制作可设计的UIImage

时间:2018-02-07 09:11:47

标签: ios swift uiimageview uiimage ibdesignable

我是初学者。我想创建一个swift文件,其中包含一个代码来创建可设计的UIImage,因此我不会通过编码来编辑UI元素显示,只需在Interface builder中通过将此swift文件指定给UI类来进行编辑。

我可以在UIButton中做类似的事情,例如,如果我想制作圆角并为UIButton添加边框,我可以做这样的事情

import UIKit

@IBDesignable
class DesignableButton: UIButton {

    @IBInspectable var cornerRadiusOfButton : CGFloat = 0 {
        didSet {
            layer.cornerRadius = cornerRadiusOfButton
        }
    }

    @IBInspectable var borderWidth: CGFloat {
        set {
            layer.borderWidth = newValue
        }
        get {
            return layer.borderWidth
        }
    }

    @IBInspectable var borderColor: UIColor? {
        set {
            guard let uiColor = newValue else { return }
            layer.borderColor = uiColor.cgColor
        }
        get {
            guard let color = layer.borderColor else { return nil }
            return UIColor(cgColor: color)
        }
    }


}

对于UIImage,通常我们想要使用此代码添加圆角或制作圆形UIImage

// round corner
        someImage.layer.cornerRadius = checkinPhoto.bounds.width/20
        someImage.clipsToBounds = true

 //  circular image
        someImage.layer.cornerRadius = someImage.frame.size.width / 2
        someImage.clipsToBounds = true

如何将这些代码设置为UIImage的@IBDesignable代码类,如上面的Designable UIButton?我试图通过子类化UIImage来制作,但我不知道为什么我无法访问layerclipToBounds

1 个答案:

答案 0 :(得分:4)

您无法使用UIImage作为可设计对象,因为UIImage不是UIView子类,您需要将UIImageView改为UIImageUIImageView无法呈现自己需要呈现import UIKit @IBDesignable class RoundableImageView: UIImageView { @IBInspectable var cornerRadius : CGFloat = 0.0{ didSet{ self.applyCornerRadius() } } @IBInspectable var borderColor : UIColor = UIColor.clear{ didSet{ self.applyCornerRadius() } } @IBInspectable var borderWidth : Double = 0{ didSet{ self.applyCornerRadius() } } @IBInspectable var circular : Bool = false{ didSet{ self.applyCornerRadius() } } func applyCornerRadius() { if(self.circular) { self.layer.cornerRadius = self.bounds.size.height/2 self.layer.masksToBounds = true self.layer.borderColor = self.borderColor.cgColor self.layer.borderWidth = CGFloat(self.borderWidth) }else { self.layer.cornerRadius = cornerRadius self.layer.masksToBounds = true self.layer.borderColor = self.borderColor.cgColor self.layer.borderWidth = CGFloat(self.borderWidth) } } override func awakeFromNib() { super.awakeFromNib() self.applyCornerRadius() } override func layoutSubviews() { super.layoutSubviews() applyCornerRadius() } }

使用此课程

k