舍入UIImage并添加边框 [英] Rounding UIImage and adding a border

查看:163
本文介绍了舍入UIImage并添加边框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

so I want to show some pictures as annotations on the map. In order to do that I need to add the image property of the MKAnnotationView. I'm using the regular images but I want them to be rounded and with a border. So I found a way to round UIImage and I found the way to add a border to UIImage, but border doesn't seem to add (I'm not actually having the image on the screen, maybe that is the problem?).

我使用了这个答案 https://stackoverflow.com/a/29047372 / 4665643 略微修改了边框。即:

I used this answer https://stackoverflow.com/a/29047372/4665643 with a slight modification for border. Namely:

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

但我在地图上的图片没有任何边框。有什么建议吗?

But my image on the map doesn't have any border. Any suggestions ?

推荐答案

如果您想为图片添加边框,您需要确保添加一些额外的空间否则你的边框将被置于图像的顶部。解决方案是将笔画宽度的两倍添加到图像的宽度和高度,并将contentMode更改为 .Center

If you would like to add a border to your image you need to make sure you add some extra room to it otherwise your border will be placed in top of your image. The solution is to add twice the width of your stroke to your image's width and height, and change the contentMode to .Center.

extension UIImage {
    func roundedWithBorder(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: .zero, size: square))
        imageView.contentMode = .center
        imageView.image = self
        imageView.layer.cornerRadius = square.width/2
        imageView.layer.masksToBounds = true
        imageView.layer.borderWidth = width
        imageView.layer.borderColor = color.cgColor
        UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, false, scale)
        defer { UIGraphicsEndImageContext() }
        guard let context = UIGraphicsGetCurrentContext() else { return nil }
        imageView.layer.render(in: context)
        return UIGraphicsGetImageFromCurrentImageContext()
    }
}

游乐场测试:

let profilePicture = UIImage(data: try! Data(contentsOf: URL(string:"http://i.stack.imgur.com/Xs4RX.jpg")!))!

profilePicture.roundedWithBorder(width: 100, color: .red)

这篇关于舍入UIImage并添加边框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆