我正在尝试为我拥有的 UIImage
添加边框,而不是 UIImageView
。
这是我的代码:
let textView = UITextView(frame: CGRectMake(10, 20, self.view.frame.width - 20, self.view.frame.height - 20))
let attributedString = NSMutableAttributedString(string: "")
let image1 = NSTextAttachment()
image1.image = UIImage(named: "image.jpg")
let oldWidth1 = image1.image!.size.width;
//I'm subtracting 10px to make the image display nicely, accounting
//for the padding inside the textView
let scaleFactor1 = oldWidth1 / (textView.frame.size.width - 10 )
image1.image = UIImage(CGImage: image1.image!.CGImage!, scale: scaleFactor1, orientation: .Up)
let attrStringWithImage1 = NSAttributedString(attachment: image1)
attributedString.replaceCharactersInRange(NSMakeRange(0, 0), withAttributedString: attrStringWithImage1)
textView.attributedText = attributedString;
self.view.addSubview(textView)
我有一个 UIImage
,它在 textView 中显示得很好,但现在我想为图像添加边框或一些填充,这样文本就不会太靠近图像!
最佳答案
你可以很容易地使用 Core Graphics 来做到这一点
您只需在更大的上下文中重新绘制图像以考虑边框宽度 - 并根据边框宽度偏移图像。
像这样的东西应该可以解决问题:
extension UIImage {
func imageWithBorder(borderWidth:CGFloat) -> UIImage {
// the bigger size to account for the border width
let newSize = CGSize(width: size.width+borderWidth*2.0, height: size.height+borderWidth*2.0)
// create new image context
UIGraphicsBeginImageContextWithOptions(newSize, false, scale)
// draw image with offset of the border width
self.drawInRect(CGRect(x: borderWidth, y: borderWidth, width: size.width, height: size.height))
// get image and end context
let img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return img
}
}
如果你想给边框填充颜色,你总是可以通过设置填充颜色来实现,并在绘制图像之前填充上下文。
然后你可以像这样使用它:
image1.image = UIImage(named: "image.jpg")?.imageWithBorder(10)
旁注
您似乎经常强制解包可选值。请不要。请始终安全地打开它们。 My answer here可能对此有用。
关于ios - 向 UITextView 内的 UIImage 添加边框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36535222/