목표 C(iOS)에서 이미지에 텍스트를 쓰는 방법은 무엇입니까?
다음과 같은 이미지를 프로그래밍 방식으로 만들고 싶습니다.
상단 이미지와 텍스트를 가지고 있습니다.이미지에 텍스트를 써야 합니까?
완전한 .png 이미지(이미지+라벨)로 만들어서 버튼 배경으로 설정하고 싶습니다.
이미지 내부에 텍스트를 그리고 결과 이미지를 반환합니다.
+(UIImage*) drawText:(NSString*) text
inImage:(UIImage*) image
atPoint:(CGPoint) point
{
UIFont *font = [UIFont boldSystemFontOfSize:12];
UIGraphicsBeginImageContext(image.size);
[image drawInRect:CGRectMake(0,0,image.size.width,image.size.height)];
CGRect rect = CGRectMake(point.x, point.y, image.size.width, image.size.height);
[[UIColor whiteColor] set];
[text drawInRect:CGRectIntegral(rect) withFont:font];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
용도:
// note: replace "ImageUtils" with the class where you pasted the method above
UIImage *img = [ImageUtils drawText:@"Some text"
inImage:img
atPoint:CGPointMake(0, 0)];
이미지 내부의 텍스트 원점을 0.0에서 원하는 지점으로 변경합니다.
텍스트 뒤에 단색 직사각형을 그리려면 선 앞에 다음을 추가합니다.[[UIColor whiteColor] set];
:
[[UIColor brownColor] set];
CGContextFillRect(UIGraphicsGetCurrentContext(),
CGRectMake(0, (image.size.height-[text sizeWithFont:font].height),
image.size.width, image.size.height));
텍스트 크기를 사용하여 단색 사각형의 원점을 계산하고 있지만 원하는 숫자로 바꿀 수 있습니다.
iOS 7 지원을 통한 첫 번째 답변에 대한 저의 기여:
+(UIImage*) drawText:(NSString*) text
inImage:(UIImage*) image
atPoint:(CGPoint) point
{
UIGraphicsBeginImageContextWithOptions(image.size, YES, 0.0f);
[image drawInRect:CGRectMake(0,0,image.size.width,image.size.height)];
CGRect rect = CGRectMake(point.x, point.y, image.size.width, image.size.height);
[[UIColor whiteColor] set];
UIFont *font = [UIFont boldSystemFontOfSize:12];
if([text respondsToSelector:@selector(drawInRect:withAttributes:)])
{
//iOS 7
NSDictionary *att = @{NSFontAttributeName:font};
[text drawInRect:rect withAttributes:att];
}
else
{
//legacy support
[text drawInRect:CGRectIntegral(rect) withFont:font];
}
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
이것이 도움이 되길 바랍니다.
편집: 수정됨UIGraphicsBeginImageContextWithOptions
화면 축척을 처리합니다.Thk @SoftDesigner
여기 스위프트 버전이 있습니다.
func textToImage(drawText: NSString, inImage: UIImage, atPoint:CGPoint)->UIImage{
// Setup the font specific variables
var textColor: UIColor = UIColor.whiteColor()
var textFont: UIFont = UIFont(name: "Helvetica Bold", size: 12)!
//Setup the image context using the passed image.
UIGraphicsBeginImageContext(inImage.size)
//Setups up 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))
// Creating a point within the space that is as bit as the image.
var rect: CGRect = CGRectMake(atPoint.x, atPoint.y, inImage.size.width, inImage.size.height)
//Now Draw the text into an image.
drawText.drawInRect(rect, withAttributes: textFontAttributes)
// Create a new image out of the images we have created
var newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()
// End the context now that we have the image we need
UIGraphicsEndImageContext()
//And pass it back up to the caller.
return newImage
}
그것을 말하자면, 당신은 그냥 이미지를 전달할 뿐입니다.
textToImage("000", inImage: UIImage(named:"thisImage.png")!, atPoint: CGPointMake(20, 20))
다음 링크는 이 문제를 해결하는 데 도움이 되었습니다.
Swift - drawInRect: 속성을 사용하여 텍스트 그리기:
목표 C(iOS)에서 이미지에 텍스트를 쓰는 방법은 무엇입니까?
원래의 목표는 지도에서 주어진 위치에 가격을 넣는 것과 같이 Annotion View에서 사용할 수 있는 동적 이미지를 만드는 것이었고 이것은 매우 효과적이었습니다.이것이 같은 일을 하려는 누군가에게 도움이 되기를 바랍니다.
iOS7만 해당.
오른쪽 하단 모서리에 워터마크가 있습니다.
@interface UIImage (DrawWatermarkText)
-(UIImage*)drawWatermarkText:(NSString*)text;
@end
@implementation UIImage (DrawWatermarkText)
-(UIImage*)drawWatermarkText:(NSString*)text {
UIColor *textColor = [UIColor colorWithWhite:0.5 alpha:1.0];
UIFont *font = [UIFont systemFontOfSize:50];
CGFloat paddingX = 20.f;
CGFloat paddingY = 20.f;
// Compute rect to draw the text inside
CGSize imageSize = self.size;
NSDictionary *attr = @{NSForegroundColorAttributeName: textColor, NSFontAttributeName: font};
CGSize textSize = [text sizeWithAttributes:attr];
CGRect textRect = CGRectMake(imageSize.width - textSize.width - paddingX, imageSize.height - textSize.height - paddingY, textSize.width, textSize.height);
// Create the image
UIGraphicsBeginImageContext(imageSize);
[self drawInRect:CGRectMake(0, 0, imageSize.width, imageSize.height)];
[text drawInRect:CGRectIntegral(textRect) withAttributes:attr];
UIImage *resultImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return resultImage;
}
@end
용도:
UIImage *image = [UIImage imageNamed:@"mona_lisa"];
image = [image drawWatermarkText:@"Leonardo da Vinci"];
이런 거 했어요.몇 가지 예제를 검색하고 결합한 후에.
필요한 경우 텍스트를 이미지 중앙에 놓고 글꼴 크기를 조정합니다.
UIImage *myImage = [UIImage imageNamed:@"promoicon.png"];
UIGraphicsBeginImageContext(myImage.size);
[myImage drawInRect:CGRectMake(0,0,myImage.size.width,myImage.size.height)];
UITextView *myText = [[UITextView alloc] init];
myText.font = [UIFont fontWithName:@"TrebuchetMS-Bold" size:15.0f];
myText.textColor = [UIColor whiteColor];
myText.text = NSLocalizedString(@"promotionImageText", @"");
myText.backgroundColor = [UIColor clearColor];
CGSize maximumLabelSize = CGSizeMake(myImage.size.width,myImage.size.height);
CGSize expectedLabelSize = [myText.text sizeWithFont:myText.font
constrainedToSize:maximumLabelSize
lineBreakMode:UILineBreakModeWordWrap];
myText.frame = CGRectMake((myImage.size.width / 2) - (expectedLabelSize.width / 2),
(myImage.size.height / 2) - (expectedLabelSize.height / 2),
myImage.size.width,
myImage.size.height);
[[UIColor whiteColor] set];
[myText.text drawInRect:myText.frame withFont:myText.font];
UIImage *myNewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
스위프트에서 워터마크를 그리기 위해 UI 이미지를 완전히 사용자 정의한 확장을 만들었습니다.
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]
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)
}
/// Start creating the image with water mark
UIGraphicsBeginImageContext(imageSize)
self.drawInRect(CGRectMake(0, 0, imageSize.width, imageSize.height))
NSString(string: waterMarkText).drawInRect(textFrame, withAttributes: textAttributes)
let waterMarkedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return waterMarkedImage
}
}
보시다시피, 변경할 필요가 없는 경우 무시할 수 있도록 속성에 대한 기본값을 몇 가지 추가했습니다.다음은 사용 방법에 대한 몇 가지 예입니다.
let watermark1 = image.waterMarkedImage(waterMarkText: "@yourapp")
let watermark2 = image.waterMarkedImage(waterMarkText: "your app name", corner: .TopRight, margin: CGPoint(x: 5, y: 5), waterMarkTextColor: UIColor.greenColor())
let watermark3 = image.waterMarkedImage(waterMarkText: "appName", waterMarkTextColor: UIColor.blackColor(), waterMarkTextFont: UIFont(name: "Helvatica", size: 25)!)
Swift 4.0 버전:
extension UIImage
{
enum WaterMarkCorner
{
case TopLeft
case TopRight
case BottomLeft
case BottomRight
}
func waterMarkedImage(text:String, corner:WaterMarkCorner = .BottomRight, margin:CGPoint = CGPoint(x: 20, y: 20), color:UIColor = UIColor.white, font:UIFont = UIFont.systemFont(ofSize: 20), background:UIColor = UIColor.clear) -> UIImage?
{
let attributes = [NSAttributedStringKey.foregroundColor: color, NSAttributedStringKey.font:font]
let textSize = NSString(string: text).size(withAttributes: attributes)
var frame = CGRect(x: 0, y: 0, width: textSize.width, height: textSize.height)
let imageSize = self.size
switch corner
{
case .TopLeft:
frame.origin = margin
case .TopRight:
frame.origin = CGPoint(x: imageSize.width - textSize.width - margin.x, y: margin.y)
case .BottomLeft:
frame.origin = CGPoint(x: margin.x, y: imageSize.height - textSize.height - margin.y)
case .BottomRight:
frame.origin = CGPoint(x: imageSize.width - textSize.width - margin.x, y: imageSize.height - textSize.height - margin.y)
}
// Start creating the image with water mark
UIGraphicsBeginImageContext(imageSize)
self.draw(in: CGRect(x: 0, y: 0, width: imageSize.width, height: imageSize.height))
NSString(string: text).draw(in: frame, withAttributes: attributes)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
다음은 이미지의 텍스트 중심을 정확하게 맞추는 Swift 버전입니다.이것은 다양한 크기의 텍스트에서 작동합니다.
func addTextToImage(text: NSString, inImage: UIImage, atPoint:CGPoint) -> UIImage{
// Setup the font specific variables
let textColor = YOURCOLOR
let textFont = YOUR SIZE
//Setups up the font attributes that will be later used to dictate how the text should be drawn
let textFontAttributes = [
NSFontAttributeName: textFont,
NSForegroundColorAttributeName: textColor,
]
// Create bitmap based graphics context
UIGraphicsBeginImageContextWithOptions(inImage.size, false, 0.0)
//Put the image into a rectangle as large as the original image.
inImage.drawInRect(CGRectMake(0, 0, inImage.size.width, inImage.size.height))
// Our drawing bounds
let drawingBounds = CGRectMake(0.0, 0.0, inImage.size.width, inImage.size.height)
let textSize = text.sizeWithAttributes([NSFontAttributeName:textFont])
let textRect = CGRectMake(drawingBounds.size.width/2 - textSize.width/2, drawingBounds.size.height/2 - textSize.height/2,
textSize.width, textSize.height)
text.drawInRect(textRect, withAttributes: textFontAttributes)
// Get the image from the graphics context
let newImag = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImag
}
이 방법을 사용하여 선택한 글꼴과 색상 및 크기로 이미지에 텍스트 필드를 추가합니다.
//Method to add
- (UIImage *) addText:(UIImage *)img text:(NSString *)text
{
CGRect rect = CGRectMake(0,0, img.size.width, img.size.height);
// create a context according to image size
UIGraphicsBeginImageContext(rect.size);
// draw image
[img drawInRect:rect];
float fontSize = _txtvwEdit.font.pointSize*2;
NSLog(@"Original %f new %f",_txtvwEdit.font.pointSize,fontSize);
UIFont* font = [UIFont fontWithName:_txtvwEdit.font.fontName size:fontSize];
CGRect textRect = CGRectMake((_txtvwEdit.frame.origin.x*2)-5,_txtvwEdit.frame.origin.y*2,_txtvwEdit.frame.size.width*2,_txtvwEdit.frame.size.height*2);
if ([temparyGifframes count]>0)
{
font = [UIFont fontWithName:_txtvwEdit.font.fontName size:_txtvwEdit.font.pointSize];
textRect = CGRectMake(_txtvwEdit.frame.origin.x,_txtvwEdit.frame.origin.y ,_txtvwEdit.frame.size.width,_txtvwEdit.frame.size.height);
}
/// Make a copy of the default paragraph style
NSMutableParagraphStyle* paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
paragraphStyle.lineBreakMode = NSLineBreakByCharWrapping;
paragraphStyle.alignment = NSTextAlignmentLeft;
NSDictionary *attributes = @{ NSFontAttributeName: font, NSForegroundColorAttributeName: _txtvwEdit.textColor,NSParagraphStyleAttributeName: paragraphStyle };
// draw text
[text drawInRect:textRect withAttributes:attributes];
// get as image
UIImage * image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
@Jano Answer의 Swift-3에서 :-
func drawText(text:NSString ,image:UIImage ,point:CGPoint ) -> UIImage {
let font = UIFont.boldSystemFont(ofSize: 12)
UIGraphicsBeginImageContext(image.size)
image.draw(in:CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height) )
let rect = CGRect(x: point.x, y: point.y, width:image.size.width, height: image.size.height )
UIColor.white.set()
text.draw(in: rect.integral, withAttributes: [NSFontAttributeName : font])
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
스위프트 3
extension UIImage {
func textToImage(drawText: NSString, atPoint:CGPoint) -> UIImage? {
// Setup the font specific variables
let textColor: UIColor = UIColor.white
let textFont: UIFont = UIFont(name: "Helvetica Bold", size: 12)!
//Setup the image context using the passed image.
UIGraphicsBeginImageContext(self.size)
//Setups up the font attributes that will be later used to dictate how the text should be drawn
let textFontAttributes = [
NSFontAttributeName: textFont,
NSForegroundColorAttributeName: textColor,
] as [String : Any]
//Put the image into a rectangle as large as the original image.
self.draw(in: CGRect(x:0, y:0, width:self.size.width, height: self.size.height))
// Creating a point within the space that is as bit as the image.
let rect: CGRect = CGRect(x:atPoint.x, y:atPoint.y, width:self.size.width, height:self.size.height)
//Now Draw the text into an image.
drawText.draw(in: rect, withAttributes: textFontAttributes)
// Create a new image out of the images we have created
let newImage: UIImage? = UIGraphicsGetImageFromCurrentImageContext()
// End the context now that we have the image we need
UIGraphicsEndImageContext()
//And pass it back up to the caller.
return newImage
}
}
@Hossam Gareebs의 Swift 3 버전이 응답하고 backgroundColor 매개 변수의 누락된 통합을 추가했습니다.
enum WaterMarkCorner{
case TopLeft
case TopRight
case BottomLeft
case BottomRight
}
extension UIImage{
func waterMarkedImage(_ waterMarkText:String, corner:WaterMarkCorner = .TopRight, margin:CGPoint = CGPoint(x: 20, y: 20), waterMarkTextColor:UIColor = UIColor.black, waterMarkTextFont:UIFont = UIFont.systemFont(ofSize: 40), backgroundColor:UIColor = UIColor(white: 1.0, alpha: 0.5)) -> UIImage?{
let textAttributes = [NSForegroundColorAttributeName:waterMarkTextColor, NSFontAttributeName:waterMarkTextFont, NSBackgroundColorAttributeName: backgroundColor]
let textSize = NSString(string: waterMarkText).size(attributes: textAttributes)
var textFrame = CGRect(x:0, y:0, width:textSize.width, height: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)
}
/// Start creating the image with water mark
UIGraphicsBeginImageContext(imageSize)
self.draw(in: CGRect(x:0, y:0, width:imageSize.width, height:imageSize.height))
NSString(string: waterMarkText).draw(in: textFrame, withAttributes: textAttributes)
let waterMarkedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return waterMarkedImage
}
}
내 기능은 45도 및 90도 회전으로 이미지에 텍스트 워터마크를 추가할 수 있습니다.
+(UIImage *)drawText:(NSString *)text diagonallyOnImage:(UIImage *)image rotation:(WatermarkRotation)rotation{
UIColor *textColor = [UIColor colorWithRed:255 green:0 blue:0 alpha:0.2];//[UIColor colorWithWhite:0.5 alpha:1.0];
UIFont *font = [UIFont systemFontOfSize:250];
// Compute rect to draw the text inside
NSDictionary *attr = @{NSForegroundColorAttributeName: textColor, NSFontAttributeName: font};
CGSize textSize = [text sizeWithAttributes:attr];
CGSize imageSize = image.size;
// Create a bitmap context into which the text will be rendered.
UIGraphicsBeginImageContext(textSize);
// Render the text
[text drawAtPoint:CGPointMake(0,0) withAttributes:attr];
// Retrieve the image
UIImage* img = UIGraphicsGetImageFromCurrentImageContext();
CGImageRef imageRef = [img CGImage];
CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(imageRef);
CGColorSpaceRef colorSpaceInfo = CGImageGetColorSpace(imageRef);
CGContextRef bitmap = CGBitmapContextCreate(NULL, textSize.width, textSize.width, CGImageGetBitsPerComponent(imageRef), CGImageGetBytesPerRow(imageRef), colorSpaceInfo, bitmapInfo);
switch (rotation) {
case WatermarkRotation90left:
CGContextRotateCTM (bitmap, DEGREES_RADIANS(-90));
CGContextTranslateCTM(bitmap, -textSize.width, 0);
break;
case WatermarkRotation90right:
CGContextRotateCTM (bitmap, DEGREES_RADIANS(90));
CGContextTranslateCTM(bitmap, 0, -textSize.width);
break;
case WatermarkRotation45ltr:
CGContextRotateCTM (bitmap, DEGREES_RADIANS(45));
CGContextTranslateCTM(bitmap, textSize.width/4, -textSize.width/2);
break;
case WatermarkRotation45rtl:
CGContextRotateCTM (bitmap, DEGREES_RADIANS(-45));
CGContextTranslateCTM(bitmap, -textSize.width/2, textSize.width/4);
break;
default:
break;
}
CGContextDrawImage(bitmap, CGRectMake(0, (textSize.width/2)-(textSize.height/2), textSize.width, textSize.height), imageRef);
CGImageRef ref = CGBitmapContextCreateImage(bitmap);
UIImage* newImage = [UIImage imageWithCGImage:ref];
UIGraphicsBeginImageContext( imageSize );
// Use existing opacity as is
[image drawInRect:CGRectMake(0,0,imageSize.width,imageSize.height)];
if (rotation == WatermarkRotation90left) {
[newImage drawInRect:CGRectMake(-((textSize.width/2)-(textSize.height/2)),(imageSize.height/2)-(textSize.width/2),textSize.width,textSize.width) blendMode:kCGBlendModeNormal alpha:1.0];
}else if(rotation == WatermarkRotation90right){
[newImage drawInRect:CGRectMake((imageSize.width-textSize.width/2)-(textSize.height/2),(imageSize.height/2)-(textSize.width/2),textSize.width,textSize.width) blendMode:kCGBlendModeNormal alpha:1.0];
}else{
[newImage drawInRect:CGRectMake((imageSize.width/2)-(textSize.width/2),(imageSize.height/2)-(textSize.width/2),textSize.width,textSize.width) blendMode:kCGBlendModeNormal alpha:1.0];
}
UIImage *mergedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return mergedImage;
}
회전을 위한 열거형:
typedef enum:NSUInteger{
WatermarkRotation90left=1,
WatermarkRotation90right,
WatermarkRotation45ltr,
WatermarkRotation45rtl
}WatermarkRotation;
참고: 이미지 중앙에 워터마크를 그리려면 0을 사용합니다.(스위치 문의 기본 대소문자)
라디안에 학위를 위한 이 매크로 추가:
#define DEGREES_RADIANS(angle) ((angle) / 180.0 * M_PI)
이것이 도움이 되길 바랍니다!!!
할 때, 전화하는 것을 피해야 합니다.-drawRect:
.ㅠㅠUIView
는 의지받습으로 지원됩니다.CALayer
.CALayer
계층에 유지됩니다., 및 조정을 sy, "/"/" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "", 추가, 추가를 할 수 .CATextLayer
UIImageView
워터마크가 있는 이미지가 필요하지 않은 경우.https://developer.apple.com/library/ios/qa/qa1708/_index.html
CATextLayer *textLayer = [CATextLayer layer];
UIFont *font = [UIFont systemFontOfSize:14.0f];
CGSize textSize = [text sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14.0f]}];
textLayer.frame = CGRectMake((imageView.size.width - textSize.width)/2,
(imageView.size.height - textSize.height)/2,
textSize.width, textSize.height);;
textLayer.string = text;
textLayer.fontSize = font.pointSize;
[imageView.layer addSublayer:textLayer];
}
저는 @harish-pathak에서 제공한 예제를 기반으로 솔루션을 구축했습니다.HiDPI 합니다(HiDPI 디스 고려다니합를치장는가이있레플(▁with▁ithi다size
인 반면에 반에면은 int입니다.left
그리고.top
백분율은 두 배)입니다.
-(UIImage *)drawText:(NSString *)text onImage:(UIImage *)image withSize:(NSInteger)size posLeft:(double)left posTop:(double)top {
// Get UI scale for HiDPI
CGFloat scale = [[UIScreen mainScreen] scale];
UIColor *textColor = [UIColor whiteColor];
UIFont *font = [UIFont fontWithName:@"Font-Name" size:size];
// Compute rect to draw the text inside
NSDictionary *attr = @{NSForegroundColorAttributeName: textColor, NSFontAttributeName: font};
CGSize textSize = [text sizeWithAttributes:attr];
CGSize imageSize = image.size;
// Create a bitmap context into which the text will be rendered
UIGraphicsBeginImageContextWithOptions(textSize, NO, scale);
// Render the text
[text drawAtPoint:CGPointMake(0,0) withAttributes:attr];
// Retrieve the image
UIImage* img = UIGraphicsGetImageFromCurrentImageContext();
CGImageRef imageRef = [img CGImage];
CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(imageRef);
CGColorSpaceRef colorSpaceInfo = CGImageGetColorSpace(imageRef);
// Create bitmap context for text
CGFloat scaledTextWidth = textSize.width * scale;
CGFloat scaledTextHeight = textSize.height * scale;
CGContextRef textBitmap = CGBitmapContextCreate(NULL, scaledTextWidth, scaledTextHeight, CGImageGetBitsPerComponent(imageRef), CGImageGetBytesPerRow(imageRef), colorSpaceInfo, bitmapInfo);
// Scale text for HiDPI devices
CGContextScaleCTM(textBitmap, scale, scale);
// Draw image for text
CGRect textPosition = CGRectMake(0, 0, textSize.width, textSize.height);
CGRect textPixelAligned = CGRectIntegral(textPosition);
CGContextDrawImage(textBitmap, textPixelAligned, imageRef);
CGImageRef ref = CGBitmapContextCreateImage(textBitmap);
UIImage* newImage = [UIImage imageWithCGImage:ref];
// Create bitmap context into which the image will be rendered
UIGraphicsBeginImageContextWithOptions(imageSize, NO, scale);
// Use existing opacity as is
[image drawInRect:CGRectMake(0,0,imageSize.width,imageSize.height)];
// Create new image with blendmode "normal"
CGFloat textLeft = (imageSize.width*left)-(textSize.width*0.5);
CGFloat textTop = (imageSize.height*top)-(textSize.height*0.5);
CGRect imagePosition = CGRectMake(textLeft,textTop,textSize.width,textSize.height);
CGRect imagePixelAligned = CGRectIntegral(imagePosition);
[newImage drawInRect:imagePixelAligned blendMode:kCGBlendModeNormal alpha:1.0];
// Get merged image from context
UIImage *mergedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return mergedImage;
}
이미지 중앙에 텍스트를 배치하려면 다음과 같이 함수를 호출합니다.
[self drawText:@"Text" onImage:img withSize:120 posLeft:0.5 posTop:0.5];
학점:
- 목표-C에서 이미지 위에 텍스트를 프로그래밍 방식으로 배치
- UI 이미지와 텍스트 위에 텍스트를 배치하는 것이 흐릿합니까?
- Retina 디스플레이에서 작동하는 CGBitmapContext를 만드는 방법
UIImageView *imageView = [UIImageView alloc];
imageView.image = [UIImage imageNamed:@"img.png"];
UILabel *label = [UILabel alloc];
label.text = @"Your text";
[imageView addsubview:label];
레이블을 표시할 레이블의 프레임을 설정합니다.
언급URL : https://stackoverflow.com/questions/6992830/how-to-write-text-on-image-in-objective-c-ios
'source' 카테고리의 다른 글
Global.asax를 디버깅할 수 있습니까? (0) | 2023.08.02 |
---|---|
텍스트 편집 필드가 비어 있는지 확인하려면 어떻게 합니까? (0) | 2023.08.02 |
Android Emulator의 스토리지를 늘리는 방법 (INSTALL_FAILED_)_스토리지 부족) (0) | 2023.08.02 |
'void' 유형은 'Observable' 유형에 할당할 수 없습니다.입력 <{}> (0) | 2023.08.02 |
현재 커서 위치의 텍스트 영역에 텍스트를 삽입하는 방법은 무엇입니까? (0) | 2023.08.02 |