在UITextView内向UIImage添加边框

时间:2016-04-10 20:31:35

标签: 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中很好地显示,但现在我想在图像中添加边框或一些填充,这样文本就不会如此接近图像了!

1 个答案:

答案 0 :(得分:6)

您可以轻松使用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可能对此有用。