Adding padding and border to an UIImageView

后端 未结 2 554
梦谈多话
梦谈多话 2021-01-04 11:13

How can I add padding between an UIImageView and its border?

Img.layer.cornerRadius = Img.bounds.width / 2
Img.layer.borderWidth = 2
Img.layer.         


        
2条回答
  •  梦谈多话
    2021-01-04 11:30

    As per the 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
        }
    }
    

提交回复
热议问题