添加填充和边框到UIImageView

时间:2017-09-27 00:04:03

标签: ios swift3 uiimageview uiimage

如何在UIImageView及其边框之间添加填充?

    Img.layer.cornerRadius = Img.bounds.width / 2
    Img.layer.borderWidth = 2
    Img.layer.borderColor = UIColor.blue.cgColor
    Img.clipsToBounds = true

像这样:

enter image description here

2 个答案:

答案 0 :(得分:10)

根据this link

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        let image = UIImage(named: "imagename")!
        let imageView = UIImageView(image: image.imageWithInsets(insets: UIEdgeInsetsMake(30, 30, 30, 30)))
        imageView.frame = CGRect(x: 0, y: 0, width: 300, height: 400)
        imageView.backgroundColor = UIColor.gray
        imageView.layer.borderWidth = 2
        imageView.layer.borderColor = UIColor.blue.cgColor
        view.addSubview(imageView)
    }
}
extension UIImage {
    func imageWithInsets(insets: UIEdgeInsets) -> UIImage? {
        UIGraphicsBeginImageContextWithOptions(
            CGSize(width: self.size.width + insets.left + insets.right,
                   height: self.size.height + insets.top + insets.bottom), false, self.scale)
        let _ = UIGraphicsGetCurrentContext()
        let origin = CGPoint(x: insets.left, y: insets.top)
        self.draw(at: origin)
        let imageWithInsets = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return imageWithInsets
    }
}

答案 1 :(得分:0)

要向UIImageView的UIImage添加填充,请在Swift中使用以下代码

/* Change autocomplete styles in WebKit */
input:-webkit-autofill,
input:-webkit-autofill:hover, 
input:-webkit-autofill:focus,
textarea:-webkit-autofill,
textarea:-webkit-autofill:hover,
textarea:-webkit-autofill:focus,
select:-webkit-autofill,
select:-webkit-autofill:hover,
select:-webkit-autofill:focus {
  border: 1px solid green;
  -webkit-text-fill-color: green;
  -webkit-box-shadow: 0 0 0px 1000px #000 inset;
}