将填充和边框添加到UIImageView中
问题描述:
如何在UIImageView和边框之间添加填充?将填充和边框添加到UIImageView中
Img.layer.cornerRadius = Img.bounds.width/2
Img.layer.borderWidth = 2
Img.layer.borderColor = UIColor.blue.cgColor
Img.clipsToBounds = true
像这样:
答
由于每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
}
}
+0
什么是view.addSubview(imageView)中的“视图”应该是?这是给我一个错误。我需要将UIView添加到图像吗? – ILoveToCode22
+0
它只是ViewController中的视图。 –
请检查https://*.com/questions/20021478/add-transparent-space-around -a-uiimage –