how to add colored border to uiimage in swift

后端 未结 5 1651
礼貌的吻别
礼貌的吻别 2020-12-31 15:59

It is pretty easy to add border to UIImageView, using layers (borderWidth, borderColor etc.). Is there any possibility to add border to image, not to image view? Does somebo

5条回答
  •  生来不讨喜
    2020-12-31 16:43

    Here is the way how you can achieve that:

    Add below extension to your code:

    extension UIImage {
        func imageWithBorder(width: CGFloat, color: UIColor) -> UIImage? {
            let square = CGSize(width: min(size.width, size.height) + width * 2, height: min(size.width, size.height) + width * 2)
            let imageView = UIImageView(frame: CGRect(origin: CGPoint(x: 0, y: 0), size: square))
            imageView.contentMode = .center
            imageView.image = self
            imageView.layer.borderWidth = width
            imageView.layer.borderColor = color.cgColor
            UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, false, scale)
            guard let context = UIGraphicsGetCurrentContext() else { return nil }
            imageView.layer.render(in: context)
            let result = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            return result
        }
    }
    

    And you can use it this way:

    let imgOriginal = UIImage.init(named: "Richie_Rich")
    img.image = imgOriginal?.imageWithBorder(width: 2, color: UIColor.blue)
    

    And result will be:

    Here is the original post which is with Round corners but I removed that code because you did't ask for it.

提交回复
热议问题