ios – 舍入UIImage并添加边框

所以我想在地图上显示一些图片作为注释.为此,我需要添加MKAnnotationView的image属性.我正在使用常规图像,但我希望它们是圆形的并带有边框.所以我找到了一种圆形UI Image的方法,我找到了为UIImage添加边框的方法,但是边框似乎没有添加(我实际上并没有在屏幕上显示图像,也许这就是问题?).

我使用这个答案https://stackoverflow.com/a/29047372/4665643稍作修改边框.即:

imageView.layer.borderWidth = 1.5
imageView.layer.borderColor = UIColor.whiteColor().CGColor
imageView.clipsToBounds = true

但我在地图上的图像没有任何边框.有什么建议 ?

解决方法

如果您想为图片添加边框,则需要确保为其添加一些额外的空间,否则您的边框将放置在图像的顶部.解决方案是将笔划宽度的两倍添加到图像的宽度和高度.
extension UIImage {
    var isPortrait:  Bool    { return size.height > size.width }
    var isLandscape: Bool    { return size.width > size.height }
    var breadth:     CGFloat { return min(size.width,size.height) }
    var breadthSize: CGSize  { return CGSize(width: breadth,height: breadth) }
    var breadthRect: CGRect  { return CGRect(origin: .zero,size: breadthSize) }
    func rounded(with color: UIColor,width: CGFloat) -> UIImage? {
        let bleed = breadthRect.insetBy(dx: -width,dy: -width)
        UIGraphicsBeginImageContextWithOptions(bleed.size,false,scale)
        defer { UIGraphicsEndImageContext() }
        guard let cgImage = cgImage?.cropping(to: CGRect(origin: CGPoint(
            x: isLandscape ? ((size.width-size.height)/2).rounded(.down) : 0,y: isPortrait  ? ((size.height-size.width)/2).rounded(.down) : 0),size: breadthSize))
        else { return nil }
        UIBezierPath(ovalIn: CGRect(origin: .zero,size: bleed.size)).addClip()
        var strokeRect =  breadthRect.insetBy(dx: -width/2,dy: -width/2)
        strokeRect.origin = CGPoint(x: width/2,y: width/2)
        UIImage(cgImage: cgImage,scale: 1,orientation: imageOrientation).draw(in: strokeRect.insetBy(dx: width/2,dy: width/2))
        color.set()
        let line = UIBezierPath(ovalIn: strokeRect)
        line.lineWidth = width
        line.stroke()
        return UIGraphicsGetImageFromCurrentImageContext()
    }
}

游乐场测试:

let profilePicture = UIImage(data: try! Data(contentsOf: URL(string:"http://i.stack.imgur.com/Xs4RX.jpg")!))!
let pp = profilePicture.rounded(with: .red,width: 10)

相关文章

当我们远离最新的 iOS 16 更新版本时,我们听到了困扰 Apple...
欧版/美版 特别说一下,美版选错了 可能会永久丧失4G,不过只...
一般在接外包的时候, 通常第三方需要安装你的app进行测...
前言为了让更多的人永远记住12月13日,各大厂都在这一天将应...