How to Write Text on Image in Objective-C (Ios)

How to write text on image in Objective-C (iOS)?

Draw text inside an image and return the resulting image:

+(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;
}

Usage:

// note: replace "ImageUtils" with the class where you pasted the method above
UIImage *img = [ImageUtils drawText:@"Some text"
inImage:img
atPoint:CGPointMake(0, 0)];

Change the origin of the text inside the image from 0,0 to whatever point you like.

To paint a rectangle of solid color behind the text, add the following before the line [[UIColor whiteColor] set];:

[[UIColor brownColor] set];
CGContextFillRect(UIGraphicsGetCurrentContext(),
CGRectMake(0, (image.size.height-[text sizeWithFont:font].height),
image.size.width, image.size.height));

I'm using the text size to calculate the origin for the solid color rectangle, but you can replace it with any number.

Putting text over an image programmatically in Objective-C

It took forever, but I figured it out.

Code:

NSMutableDictionary *stringAttributes = [NSMutableDictionary dictionary];

[stringAttributes setObject: [UIFont fontWithName:@"Avenir Book" size:250] forKey: NSFontAttributeName];
[stringAttributes setObject: [UIColor whiteColor] forKey: NSForegroundColorAttributeName];

NSString *placeString = [NSString stringWithFormat:@"Text here."];

CGSize size = [placeString sizeWithAttributes:stringAttributes];
//Create a bitmap context into which the text will be rendered.
UIGraphicsBeginImageContext(size);
//Render the text.
[placeString drawAtPoint:CGPointMake(0.0, 0.0) withAttributes:stringAttributes];
//Retrieve the image.
UIImage *imagene = UIGraphicsGetImageFromCurrentImageContext();

UIImage *mergedImage = _imageView.image;

CGSize newSize = image.size;
UIGraphicsBeginImageContext(newSize);

//Use existing opacity as is.
[mergedImage drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];

//Apply supplied opacity if applicable.
CGRect drawingRect = (CGRect) {.size = size};
drawingRect.origin.x = (newSize.width - size.width) * 0.01;
drawingRect.origin.y = (newSize.height - size.height) * 0.03;
[imagene drawInRect:drawingRect blendMode:kCGBlendModeNormal alpha:1];

UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();

[_imageView setImage:newImage];
self.imageView.image = newImage;

How to write a text on image iOS?

EDIT: This can only be run on the main thread! So it's pretty much useless.

+(UIImage *)imageFromView:(UIView *)view
{
UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 0.0);
[view.layer renderInContext:UIGraphicsGetCurrentContext()];

UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

return image;
}

Here's a new one using Core Graphics that can be used on any thread

+ (UIImage *)imageFromView:(UIView *)view
{
size_t width = view.bounds.size.width*2;
size_t height = view.bounds.size.height*2;

unsigned char *imageBuffer = (unsigned char *)malloc(width*height*8);
CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef imageContext = CGBitmapContextCreate(imageBuffer, width, height, 8, width*4, colourSpace,kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Big);

CGColorSpaceRelease(colourSpace);

CGContextTranslateCTM(imageContext, 0.0, height);
CGContextScaleCTM(imageContext, 2.0, -2.0);

[view.layer renderInContext:imageContext];

CGImageRef outputImage = CGBitmapContextCreateImage(imageContext);
UIImage *image = [[UIImage alloc] initWithCGImage:outputImage];

CGImageRelease(outputImage);
CGContextRelease(imageContext);
free(imageBuffer);

return image;
}

Set Image inline with text to UITextView in Objective C

You need to just use 'UIBezierPath'

For example,

txtvHtmlString.text = @“your long text…….”;

imgView = [[UIImageView alloc] initWithFrame:CGRectMake(120, 100, 152, 128)];

imgView.image = [UIImage imageNamed:@"smily.png"];
imgView.layer.cornerRadius = 10;
[txtvHtmlString addSubview:imgView];

Then don't forget to update bezierpath in viewDidLayoutSubviews if your text is updated.

- (void)viewDidLayoutSubviews {
    UIBezierPath *exclusionPath = [UIBezierPath bezierPathWithRect:imgView.frame];
    txtvHtmlString.textContainer.exclusionPaths  = @[exclusionPath];
}

how to add text on image and move that text to different points(objective-c)

https://github.com/kcandr/IQLabelView
This one is the best approach and it worked fine for me by making the required changes to the code.

how can i add image and text in a UIButton programmatically(objective c)

The code below represents one way to create a UIButton programmatically in Objective C.

UIButton *mButton = [UIButton buttonWithType:UIButtonTypeCustom];
[mButton addTarget:self action:@selector(clickedMe:) forControlEvents:UIControlEventTouchUpInside];
[mButton setBackgroundImage:[UIImage imageNamed:@"yourImage.png"] forState:UIControlStateNormal];
[mButton setTitle:@"Show View" forState:UIControlStateNormal];
mButton.frame = CGRectMake(80.0, 210.0, 160.0, 40.0);
[yourScrollView addSubview:mButton];

Add Text on UIImage

This is my method I use for drawing text onto an image, hopefully this will help. It uses the an attributed string instead to set the properties that you want:

+(UIImage*)drawFront:(UIImage*)image text:(NSString*)text atPoint:(CGPoint)point
{
UIFont *font = [UIFont fontWithName:@"Halter" size:21];
UIGraphicsBeginImageContext(image.size);
[image drawInRect:CGRectMake(0,0,image.size.width,image.size.height)];
CGRect rect = CGRectMake(point.x, (point.y - 5), image.size.width, image.size.height);
[[UIColor whiteColor] set];

NSMutableAttributedString* attString = [[NSMutableAttributedString alloc] initWithString:text];
NSRange range = NSMakeRange(0, [attString length]);

[attString addAttribute:NSFontAttributeName value:font range:range];
[attString addAttribute:NSForegroundColorAttributeName value:[UIColor whiteColor] range:range];

NSShadow* shadow = [[NSShadow alloc] init];
shadow.shadowColor = [UIColor darkGrayColor];
shadow.shadowOffset = CGSizeMake(1.0f, 1.5f);
[attString addAttribute:NSShadowAttributeName value:shadow range:range];

[attString drawInRect:CGRectIntegral(rect)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

return newImage;
}

Should be easy enough for you to adapt to your needs... Let me know if you struggle!

How to convert Text to Image in Cocoa Objective-C

EDIT: I misread the question and assumed you wanted Cocoa-touch code (I've left it at the end in case you did). Here is one way of doing it in Cocoa using CoreText (as another poster says there are a bunch of ways):

{
NSString* string = @"Kevin";
CGFloat fontSize = 12.0f;

// Create an attributed string with string and font information
CTFontRef font = CTFontCreateWithName(CFSTR("Helvetica Light"), fontSize, nil);
NSDictionary* attributes = [NSDictionary dictionaryWithObjectsAndKeys:
(id)font, kCTFontAttributeName,
nil];
NSAttributedString* as = [[NSAttributedString alloc] initWithString:string attributes:attributes];
CFRelease(font);

// Figure out how big an image we need
CTLineRef line = CTLineCreateWithAttributedString((CFAttributedStringRef)as);
CGFloat ascent, descent, leading;
double fWidth = CTLineGetTypographicBounds(line, &ascent, &descent, &leading);

// On iOS 4.0 and Mac OS X v10.6 you can pass null for data
size_t width = (size_t)ceilf(fWidth);
size_t height = (size_t)ceilf(ascent + descent);
void* data = malloc(width*height*4);

// Create the context and fill it with white background
CGColorSpaceRef space = CGColorSpaceCreateDeviceRGB();
CGBitmapInfo bitmapInfo = kCGImageAlphaPremultipliedLast;
CGContextRef ctx = CGBitmapContextCreate(data, width, height, 8, width*4, space, bitmapInfo);
CGColorSpaceRelease(space);
CGContextSetRGBFillColor(ctx, 1.0, 1.0, 1.0, 1.0); // white background
CGContextFillRect(ctx, CGRectMake(0.0, 0.0, width, height));

// Draw the text
CGFloat x = 0.0;
CGFloat y = descent;
CGContextSetTextPosition(ctx, x, y);
CTLineDraw(line, ctx);
CFRelease(line);

// Save as JPEG
CGImageRef imageRef = CGBitmapContextCreateImage(ctx);
NSBitmapImageRep* imageRep = [[NSBitmapImageRep alloc] initWithCGImage:imageRef];
NSAssert(imageRep, @"imageRep must not be nil");
NSData* imageData = [imageRep representationUsingType:NSJPEGFileType properties:nil];
NSString* fileName = [NSString stringWithFormat:@"Kevin.jpg"];
NSString* fileDirectory = NSHomeDirectory();
NSString* filePath = [fileDirectory stringByAppendingPathComponent:fileName];
[imageData writeToFile:filePath atomically:YES];

// Clean up
[imageRep release];
CGImageRelease(imageRef);
free(data);
}

This is the cocoa-touch version:

// Figure out the dimensions of the string in a given font.
NSString* kevin = @"Kevin";
UIFont* font = [UIFont systemFontOfSize:12.0f];
CGSize size = [kevin sizeWithFont:font];
// Create a bitmap context into which the text will be rendered.
UIGraphicsBeginImageContext(size);
// Render the text
[kevin drawAtPoint:CGPointMake(0.0, 0.0) withFont:font];
// Retrieve the image
UIImage* image = UIGraphicsGetImageFromCurrentImageContext();
// Convert to JPEG
NSData* data = UIImageJPEGRepresentation(image, 1.0);
// Figure out a safe path
NSArray *arrayPaths = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory,
NSUserDomainMask,
YES);
NSString *docDir = [arrayPaths objectAtIndex:0];
// Write the file
NSString *filePath = [docDir stringByAppendingPathComponent:@"Kevin.jpg"];
BOOL success = [data writeToFile:filePath atomically:YES];
if(!success)
{
NSLog(@"Failed to write to file. Perhaps it already exists?");
}
else
{
NSLog(@"JPEG file successfully written to %@", filePath);
}
// Clean up
UIGraphicsEndImageContext();

When I made started iOS programming I found the following things unintuitive or unusual. The methods to measure and draw strings are methods on NSString (not the graphics context as in other systems). The method to save the data is a method on NSData not a file class! The functions to create the graphics context are plain C functions and not part of any class.

Hope this helps!



Related Topics



Leave a reply



Submit