iOS Swift에서 이미지에 텍스트를 추가하려면 어떻게 해야 합니까?
주변을 둘러보았는데 텍스트를 어떻게 찍어 이미지 위에 덧씌우고 둘을 하나로 묶는지 알아내지 못했습니다.UIImage
.
저는 제가 생각할 수 있는 검색어를 사용하여 구글을 지쳤기 때문에 누군가가 해결책을 가지고 있거나 최소한 그들이 그것을 가리킬 수 있는 힌트를 가지고 있다면 매우 감사할 것입니다.
알아냈어요
func textToImage(drawText: NSString, inImage: UIImage, atPoint: CGPoint) -> UIImage{
// Setup the font specific variables
var textColor = UIColor.whiteColor()
var textFont = UIFont(name: "Helvetica Bold", size: 12)!
// Setup the image context using the passed image
let scale = UIScreen.mainScreen().scale
UIGraphicsBeginImageContextWithOptions(inImage.size, false, scale)
// Setup the font attributes that will be later used to dictate how the text should be drawn
let textFontAttributes = [
NSFontAttributeName: textFont,
NSForegroundColorAttributeName: textColor,
]
// Put the image into a rectangle as large as the original image
inImage.drawInRect(CGRectMake(0, 0, inImage.size.width, inImage.size.height))
// Create a point within the space that is as bit as the image
var rect = CGRectMake(atPoint.x, atPoint.y, inImage.size.width, inImage.size.height)
// Draw the text into an image
drawText.drawInRect(rect, withAttributes: textFontAttributes)
// Create a new image out of the images we have created
var newImage = UIGraphicsGetImageFromCurrentImageContext()
// End the context now that we have the image we need
UIGraphicsEndImageContext()
//Pass the image back up to the caller
return newImage
}
라고 부르려면 이미지를 넘겨야 합니다.
textToImage("000", inImage: UIImage(named:"thisImage.png")!, atPoint: CGPointMake(20, 20))
다음 링크를 통해 이 문제를 해결할 수 있었습니다.
Swift - drawInRect:with속성이 있는 텍스트 그리기:
Objective-C(iOS)에서 이미지에 텍스트를 쓰는 방법?
원래 목표는 제가 사용할 수 있는 역동적인 이미지를 만드는 것이었습니다.AnnotaionView
지도의 특정 위치에 가격을 매기는 것과 같은 것들이 그것에 아주 잘 어울렸습니다.
스위프트 3의 경우:
func textToImage(drawText text: NSString, inImage image: UIImage, atPoint point: CGPoint) -> UIImage {
let textColor = UIColor.white
let textFont = UIFont(name: "Helvetica Bold", size: 12)!
let scale = UIScreen.main.scale
UIGraphicsBeginImageContextWithOptions(image.size, false, scale)
let textFontAttributes = [
NSFontAttributeName: textFont,
NSForegroundColorAttributeName: textColor,
] as [String : Any]
image.draw(in: CGRect(origin: CGPoint.zero, size: image.size))
let rect = CGRect(origin: point, size: image.size)
text.draw(in: rect, withAttributes: textFontAttributes)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
Swift 4의 경우:
func textToImage(drawText text: String, inImage image: UIImage, atPoint point: CGPoint) -> UIImage {
let textColor = UIColor.white
let textFont = UIFont(name: "Helvetica Bold", size: 12)!
let scale = UIScreen.main.scale
UIGraphicsBeginImageContextWithOptions(image.size, false, scale)
let textFontAttributes = [
NSAttributedStringKey.font: textFont,
NSAttributedStringKey.foregroundColor: textColor,
] as [NSAttributedStringKey : Any]
image.draw(in: CGRect(origin: CGPoint.zero, size: image.size))
let rect = CGRect(origin: point, size: image.size)
text.draw(in: rect, withAttributes: textFontAttributes)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
Swift 5의 경우:
func textToImage(drawText text: String, inImage image: UIImage, atPoint point: CGPoint) -> UIImage {
let textColor = UIColor.white
let textFont = UIFont(name: "Helvetica Bold", size: 12)!
let scale = UIScreen.main.scale
UIGraphicsBeginImageContextWithOptions(image.size, false, scale)
let textFontAttributes = [
NSAttributedString.Key.font: textFont,
NSAttributedString.Key.foregroundColor: textColor,
] as [NSAttributedString.Key : Any]
image.draw(in: CGRect(origin: CGPoint.zero, size: image.size))
let rect = CGRect(origin: point, size: image.size)
text.draw(in: rect, withAttributes: textFontAttributes)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
간단한 해결책:
func generateImageWithText(text: String) -> UIImage? {
let image = UIImage(named: "imageWithoutText")!
let imageView = UIImageView(image: image)
imageView.backgroundColor = UIColor.clear
imageView.frame = CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height)
let label = UILabel(frame: CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height))
label.backgroundColor = UIColor.clear
label.textAlignment = .center
label.textColor = UIColor.white
label.text = text
UIGraphicsBeginImageContextWithOptions(label.bounds.size, false, 0)
imageView.layer.render(in: UIGraphicsGetCurrentContext()!)
label.layer.render(in: UIGraphicsGetCurrentContext()!)
let imageWithText = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return imageWithText
}
CATextLayer(CATextLayer)를 수행할 수도 있습니다.
// 1
let textLayer = CATextLayer()
textLayer.frame = someView.bounds
// 2
let string = String(
repeating: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce auctor arcu quis velit congue dictum. ",
count: 20
)
textLayer.string = string
// 3
let fontName: CFStringRef = "Noteworthy-Light"
textLayer.font = CTFontCreateWithName(fontName, fontSize, nil)
// 4
textLayer.foregroundColor = UIColor.darkGray.cgColor
textLayer.isWrapped = true
textLayer.alignmentMode = kCAAlignmentLeft
textLayer.contentsScale = UIScreen.main.scale
someView.layer.addSublayer(textLayer)
https://www.raywenderlich.com/402-calayer-tutorial-for-ios-getting-started
어디서나 사용할 수 있도록 확장자를 만들었습니다.
import Foundation
import UIKit
extension UIImage {
class func createImageWithLabelOverlay(label: UILabel,imageSize: CGSize, image: UIImage) -> UIImage {
UIGraphicsBeginImageContextWithOptions(CGSize(width: imageSize.width, height: imageSize.height), false, 2.0)
let currentView = UIView.init(frame: CGRect(x: 0, y: 0, width: imageSize.width, height: imageSize.height))
let currentImage = UIImageView.init(image: image)
currentImage.frame = CGRect(x: 0, y: 0, width: imageSize.width, height: imageSize.height)
currentView.addSubview(currentImage)
currentView.addSubview(label)
currentView.layer.render(in: UIGraphicsGetCurrentContext()!)
let img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return img!
}
}
Usage : View Controller에서 크기와 추가할 레이블이 있는 곳에서는 다음과 같이 사용합니다.
let newImageWithOverlay = UIImage.createImageWithLabelOverlay(label: labelToAdd, imageSize: size, image: editedImage)
빠른 4의 경우:
func textToImage(drawText text: NSString, inImage image: UIImage, atPoint point: CGPoint) -> UIImage {
let scale = UIScreen.main.scale
UIGraphicsBeginImageContextWithOptions(image.size, false, scale)
image.draw(in: CGRect(origin: CGPoint.zero, size: image.size))
let rect = CGRect(origin: point, size: image.size)
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .center
let attrs = [NSAttributedStringKey.font: UIFont(name: "Helvetica Bold", size: 12)!,NSAttributedStringKey.foregroundColor : UIColor.white , NSAttributedStringKey.paragraphStyle: paragraphStyle]
text.draw(with: rect, options: .usesLineFragmentOrigin, attributes: attrs, context: nil)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
이 작업이 코드로만 수행되어야 한다는 것을 암시하는 질문을 처음에 볼 수 없습니다. 인터페이스 빌더에 UI 레이블을 추가하고 이미지와 동일한 길이와 너비를 제공하도록 제약 조건을 추가하는 것이 어떻겠습니까? 레이블 텍스트 삭제, 텍스트 글꼴 설정, 크기, col.필요에 따라 (필요한 최소 크기나 규모에 따라 자동 축소를 선택하는 것을 포함하여), 배경이 투명한지 확인합니다.
그런 다음 IBOutlet에 연결하고 필요에 따라 텍스트를 코드로 설정합니다(예: ViewWillAppear에서 또는 ViewModel 접근 방식을 사용하여 뷰/뷰 컨트롤러 초기화 시 설정).
저는 이 기본적인 부품을 사용해 보았습니다.효과가 있기를 바랍니다.
func imageWithText(image : UIImage, text : String) -> UIImage {
let outerView = UIView(frame: CGRect(x: 0, y: 0, width: image.size.width / 2, height: image.size.height / 2))
let imgView = UIImageView(frame: CGRect(x: 0, y: 0, width: outerView.frame.width, height: outerView.frame.height))
imgView.image = image
outerView.addSubview(imgView)
let lbl = UILabel(frame: CGRect(x: 5, y: 5, width: outerView.frame.width, height: 200))
lbl.font = UIFont(name: "HelveticaNeue-Bold", size: 70)
lbl.text = text
lbl.textAlignment = .left
lbl.textColor = UIColor.blue
outerView.addSubview(lbl)
let renderer = UIGraphicsImageRenderer(size: outerView.bounds.size)
let convertedImage = renderer.image { ctx in
outerView.drawHierarchy(in: outerView.bounds, afterScreenUpdates: true)
}
return convertedImage
}
QLP 리뷰 컨트롤러를 사용하는 것도 가능합니다..userDomainMask의 applicationsDocuments 디렉토리와 같은 URL에 imageFile을 저장하고 애플의 편집기를 열기만 하면 됩니다.그림 그리고 모양 추가, 화살표 그리고 서명까지 가능합니다.저는 다음의 게시글에서 구현에 대해 자세히 설명했습니다: https://stackoverflow.com/a/68743098/12035498
다행히 요즘은 아주 쉽습니다.
"some text".draw(in: rect)
바로 그겁니다.
언급URL : https://stackoverflow.com/questions/28906914/how-do-i-add-text-to-an-image-in-ios-swift
'sourcecode' 카테고리의 다른 글
Kubernetes 외부 MariaDB PXC 클러스터 노드 로드 밸런싱/페일오버 방법 (0) | 2023.10.05 |
---|---|
양식 데이터 다중 부분/양식 데이터에서 경계를 가져오거나 설정하는 방법 - 각도 (0) | 2023.10.05 |
mysql 테이블에서 특정 행 선택 (0) | 2023.10.05 |
moment.js 24h 형식 (0) | 2023.09.25 |
Swift 설명서 코멘트 사용방법 (0) | 2023.09.25 |