如何为UIImage而不是整个UIImageView添加边框颜色?

问题描述 投票:1回答:1

我需要在UIImage而不是周围(或周围的)UIImageView上添加彩色边框。

为此,我尝试使用以下代码,但无济于事:

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
    }
}


let myImage: UIImageView = {
       let iv = UIImageView()
        iv.image = UIImage(named: "imageOne")?.imageWithBorder(width: 0.8, color: .white)
        iv.clipsToBounds = true
        iv.translatesAutoresizingMaskIntoConstraints = false
        return iv
    }()

不幸的是,这不起作用。我要实现的目标无法实现吗?

编辑:

 let myImageView: UIImageView = {
       let iv = UIImageView()
        iv.image = UIImage(named: "imageOne")?.addBorder(to: UIImage(named: "imageOne")!, borderColor: .red)
        iv.clipsToBounds = true
        iv.layer.masksToBounds = true
        iv.translatesAutoresizingMaskIntoConstraints = false
        return iv
    }()

编辑2:

添加了图像:蓝色(即时获得但不想要的结果)与红色(我想要但未得到的结果)

Wrong (BLUE) VS Desired result(RED)

swift uiimageview uiimage swift5 border-color
1个回答
0
投票

此代码将在图像上添加边框:

func addBorder(to image: UIImage, borderColor: UIColor) -> UIImage? {
    UIGraphicsBeginImageContext(image.size)
    let rect = CGRect(origin: .zero, size: image.size)
    image.draw(in: rect, blendMode: .normal, alpha: 1.0)
    guard let context = UIGraphicsGetCurrentContext() else { return nil }
    borderColor.setStroke()
    context.stroke(rect)
    return UIGraphicsGetImageFromCurrentImageContext()
}
© www.soinside.com 2019 - 2024. All rights reserved.