html图片显示文字水印,Swift - 给图片添加文字水印(图片上写文字,并可设置位置和样式)...

想要给图片添加文字水印或者注释,我们需要实现在UIImage上写字的功能。

1,效果图如下:

(在图片左上角和右下角都添加了文字。)

c6701a672b93e303c63aefef991f0663.png

2,为方便使用,我们通过扩展UIImage类来实现添加水印功能

(文字大小,文字颜色,背景色,位置,边距都可以设置)

//--- UIImageExtension.swift ---

import UIKit

extension UIImage{

//水印位置枚举

enum WaterMarkCorner{

case TopLeft

case TopRight

case BottomLeft

case BottomRight

}

//添加水印方法

func waterMarkedImage(waterMarkText:String, corner:WaterMarkCorner = .BottomRight,

margin:CGPoint = CGPoint(x: 20, y: 20),

waterMarkTextColor:UIColor = UIColor.whiteColor(),

waterMarkTextFont:UIFont = UIFont.systemFontOfSize(20),

backgroundColor:UIColor = UIColor.clearColor()) -> UIImage{

let textAttributes = [NSForegroundColorAttributeName:waterMarkTextColor,

NSFontAttributeName:waterMarkTextFont,

NSBackgroundColorAttributeName:backgroundColor]

let textSize = NSString(string: waterMarkText).sizeWithAttributes(textAttributes)

var textFrame = CGRectMake(0, 0, textSize.width, textSize.height)

let imageSize = self.size

switch corner{

case .TopLeft:

textFrame.origin = margin

case .TopRight:

textFrame.origin = CGPoint(x: imageSize.width - textSize.width - margin.x, y: margin.y)

case .BottomLeft:

textFrame.origin = CGPoint(x: margin.x, y: imageSize.height - textSize.height - margin.y)

case .BottomRight:

textFrame.origin = CGPoint(x: imageSize.width - textSize.width - margin.x,

y: imageSize.height - textSize.height - margin.y)

}

// 开始给图片添加文字水印

UIGraphicsBeginImageContext(imageSize)

self.drawInRect(CGRectMake(0, 0, imageSize.width, imageSize.height))

NSString(string: waterMarkText).drawInRect(textFrame, withAttributes: textAttributes)

let waterMarkedImage = UIGraphicsGetImageFromCurrentImageContext()

UIGraphicsEndImageContext()

return waterMarkedImage

}

}

3,使用样例

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var imageView: UIImageView!

override func viewDidLoad() {

super.viewDidLoad()

//使用链式调用方法,给图片添加两条水印

imageView.image = UIImage(named:"bg")?

.waterMarkedImage("做最好的开发者知识平台")

.waterMarkedImage("hangge.com", corner: .TopLeft,

margin: CGPoint(x: 20, y: 20),

waterMarkTextColor: UIColor.blackColor(),

waterMarkTextFont: UIFont.systemFontOfSize(45),

backgroundColor: UIColor.clearColor())

}

override func didReceiveMemoryWarning() {

super.didReceiveMemoryWarning()

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值