ios - 向 UITextView 内的 UIImage 添加边框

标签 ios swift uiimage uitextview

我正在尝试为我拥有的 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/

相关文章:

ios - TableViewController 委托(delegate)没有被调用

ios - 调整字体大小以适合标签高度 - Swift 4、Xcode 9

iphone - 加载较小图像表示的最有效方法

swift - 在应用程序被杀死后请求使用通过 UIImagePickerController 选取的视频文件的权限

ios - presentScene() 不是 SKScene 的成员

ios - 如何将图片的 .raw 或原始字节存储到没有 png 或 jpeg 表示的本地磁盘文档文件夹

ios - 将 GMSPanoramaView 转换为 UIImage?

ios - 如何为这一层绘制CATransform3D?

ios - 相同大小级别的不同设备上的不同字体大小

ios - Xcode ARC 转换工具问题