在UITextView中为UIImage添加边框

4

我想给一个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中显示得很好,但现在我想为图像添加边框或一些填充,以便文本与图像不那么接近!


在图像之前和/或之后添加一个或两个换行符怎么样? - rmaddy
@rmaddy 你好,我知道我已经接受了下面的一个答案。但我想知道如何做到你上面提到的那个方法?这可能对其他人也有帮助!非常感谢。 - user5899631
1
只需将 @"\n\n" 添加到 attrStringWithImage1 - rmaddy
@rmaddy 非常感谢你! :) - user5899631
1个回答

6

您可以轻松使用核心图形来完成此操作

您只需要在更大的上下文中重新绘制图像以考虑边框宽度 - 并通过边框宽度偏移图像。

像这样的内容应该就可以解决问题:

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)

旁注

您似乎经常在强制解包可选项。请不要这样做。请始终安全地解包它们。我在这里的回答可能对此有用。


嘿,我想知道你是否能帮忙解决这个类似的问题?http://stackoverflow.com/questions/36580932/add-text-with-uiimage-inside-of-a-uitextview 如果可以的话,非常感谢! - user5899631

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接