4 uitextview uiimage ios swift
我试图为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)
Run Code Online (Sandbox Code Playgroud)
我有UIImage一个在textView中很好地显示的内容,但现在我想在图像中添加边框或一些填充,以便文本不会如此接近图像!
您只需在较大的上下文中重新绘制图像以考虑边框宽度 - 并按边框宽度偏移图像.
像这样的东西应该做的伎俩:
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
}
}
Run Code Online (Sandbox Code Playgroud)
如果要为边框指定填充颜色,可以始终通过设置填充颜色并在绘制图像之前填充上下文来实现.
然后你可以像这样使用它:
image1.image = UIImage(named: "image.jpg")?.imageWithBorder(10)
Run Code Online (Sandbox Code Playgroud)
你似乎很有力地展开了一些选项.请不要.请始终安全地打开它们.我的回答可能对此有用.
| 归档时间: |
|
| 查看次数: |
265 次 |
| 最近记录: |