如果你想添加您需要確保您添加一些額外空間的圖片邊框否則你的邊框將被放置在你的圖像的頂部。解決方法是將您筆畫的寬度加倍到圖像的寬度和高度,然後將contentMode更改爲.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()
}
}
遊樂場測試:在斯威夫特3
let profilePicture = UIImage(data: try! Data(contentsOf: URL(string:"http://i.stack.imgur.com/Xs4RX.jpg")!))!
profilePicture.roundedWithBorder(width: 100, color: .red)
它應該是'.maskToBounds'不'clipToBounds'? – Tj3n
嘿,所以實際上最初的答案也有這個,但它似乎仍然不起作用。 –
嗯...那麼我認爲有一個外部的看法,扭曲這個圖像的大小?,外部視圖應該更大或實際顯示邊框。我試過你的代碼,它工作完美,增加了一個邊框 – Tj3n