效果图:三中代码实现的效果差不多
Swift:代码
import UIKitclass ImageWatermarking: NSObject {static func textToImage(drawText text: String, inImage initImage: UIImage, atPoint point: CGPoint) -> UIImage {let textColor = UIColor.whitelet textFont = UIFont(name:"Helvetica", size: 26)!// 新建底部拼接区域let rect: CGRect = CGRect(x: 0, y: 0, width: initImage.size.width, height: 220)UIGraphicsBeginImageContext(rect.size)let context: CGContext = UIGraphicsGetCurrentContext()!context.setFillColor(UIColor.kHexRGBA(0x000000,0.3).cgColor)context.fill(rect)let imagebottom = UIGraphicsGetImageFromCurrentImageContext()UIGraphicsGetCurrentContext()let style = NSMutableParagraphStyle()style.lineSpacing = 6style.lineBreakMode = NSLineBreakMode.byTruncatingTail// 在底部拼接区域添加文字let textFontAttributes = [NSAttributedString.Key.font: textFont,NSAttributedString.Key.foregroundColor: textColor,NSAttributedString.Key.paragraphStyle: style] as [NSAttributedString.Key : Any]imagebottom!.draw(in: CGRect(origin: CGPoint.zero, size: imagebottom!.size))let rectText = CGRect(origin: point, size: initImage.size)text.draw(in: rectText, withAttributes: textFontAttributes)let newTextImage = UIGraphicsGetImageFromCurrentImageContext()UIGraphicsEndImageContext()// 拼接原图和新建的底部区域let topImage = initImagelet bottomImage = newTextImagelet allSize = CGSize(width: topImage.size.width, height: topImage.size.height )UIGraphicsBeginImageContext(allSize)let areaSizeTop = CGRect(x: 0, y: 0, width: topImage.size.width, height: topImage.size.height)topImage.draw(in: areaSizeTop)let areaSizeBottom = CGRect(x: 0, y: areaSizeTop.size.height-220, width: bottomImage!.size.width, height: bottomImage!.size.height)bottomImage!.draw(in: areaSizeBottom)let newImage:UIImage = UIGraphicsGetImageFromCurrentImageContext()!UIGraphicsEndImageContext()return newImage}}
Swift 调用:
let contentStr :String = currentTime +