when I do the following the resulting image is null
NSLog(#"string (%#) to base64NSData",object);
NSData *base64Data = [[object dataUsingEncoding:NSUTF8StringEncoding] base64EncodedDataWithOptions:0];
NSLog(#"NSData (%#) to UIImage",base64Data);
UIImage *image = [UIImage imageWithData:base64Data];
NSLog(#"my image is: %#",image);
How might I do this well?
Reason
I need to save an image from iOS to the Google blobstore. I need to include some metadata with the image. When I encode the string as base64 it does not work.
This is loosely a follow up to AFHTTPRequestOperationManager post multi-part request not working
Here is the code for generating image from NSString..
Implement this method....
+(UIImage *)imageFromText:(NSString *)text
{
UIFont *font = [UIFont systemFontOfSize:20.0];
CGSize size = [text sizeWithAttributes:
#{NSFontAttributeName:
[UIFont systemFontOfSize:20.0f]}];
if (UIGraphicsBeginImageContextWithOptions != NULL)
UIGraphicsBeginImageContextWithOptions(size,NO,0.0);
else
UIGraphicsBeginImageContext(size);
[text drawAtPoint:CGPointMake(0.0, 0.0) withFont:font];
// [text drawAtPoint:CGPointMake(0.0, 0.0) forWidth:CGPointMake(0, 0) withFont:font fontSize:nil lineBreakMode:NSLineBreakByWordWrapping baselineAdjustment:NSTextAlignmentCenter];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
Call this method like...
UIImage *image;
image = [self imageFromText:#"Good Morning];
//Use this image as per your requirement
I hope it work for you..
Here is UIImage category I used to fix my problem
http://hasseg.org/blog/post/692/use-unicode-emoji-as-icons-in-native-ios-apps/
You can modify method to pass extra parameters like font, color, backgroundColor as follows :
+ (UIImage *) hg_imageFromString:(NSString *)string withFont:(UIFont*)font textColor:(UIColor*)color andBgColor:(UIColor*)bgColor;
{
UILabel *label = [[UILabel alloc] init];
label.text = string;
label.opaque = NO;
if(bgColor != nil)
label.backgroundColor = bgColor;
if(color != nil)
label.textColor = color;
if(font != nil)
label.font = font;
else
label.font = [UIFont systemFontOfSize:17.0];
CGSize size = [string sizeWithAttributes:#{NSFontAttributeName: label.font}];
CGSize measuredSize = CGSizeMake(ceilf(size.width), ceilf(size.height));
label.frame = CGRectMake(0, 0, measuredSize.width, measuredSize.height);
return [UIImage hg_imageFromView:label];
}
Related
UIGraphicsBeginImageContext(targetSize);
NSString *txt = #"my String";
UIColor *txtColor = [UIColor whiteColor];
UIFont *txtFont = [UIFont systemFontOfSize:30];
NSDictionary *attributes = #{NSFontAttributeName:txtFont,NSForegroundColorAttributeName:txtColor};
[txt drawAtPoint:CGPointMake(0, 0) withAttributes:attributes];
UIImage *resultImg = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
I don't know how to fix it to make text to Center.
//Edit
I add your device but in vain
NSMutableParagraphStyle *styleCenter = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
styleCenter.alignment = kCTCenterTextAlignment;
NSDictionary *attributes = #{NSFontAttributeName:txtFont,NSForegroundColorAttributeName:txtColor,NSParagraphStyleAttributeName:styleCenter};
[txt drawInRect:CGRectMake(0, 0, targetSize.width, targetSize.height) withAttributes:attributes];
the text show at right not center, so weird
Try this:
UIGraphicsBeginImageContext(targetSize);
NSString *txt = #"my String";
UIColor *txtColor = [UIColor whiteColor];
UIFont *txtFont = [UIFont systemFontOfSize:30];
NSDictionary *attributes = #{NSFontAttributeName:txtFont, NSForegroundColorAttributeName:txtColor};
CGRect txtRect = [txt boundingRectWithSize:CGSizeZero
options:NSStringDrawingUsesLineFragmentOrigin
attributes:attributes
context:nil];
[txt drawAtPoint:CGPointMake(targetSize.width/2 - txtRect.size.width/2, targetSize.height/2 - txtRect.size.height/2) withAttributes:attributes];
UIImage *resultImg = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSMutableParagraphStyle *styleCenter = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
styleCenter.alignment = NSCenterTextAlignment;
NSDictionary *attributes = #{NSFontAttributeName:txtFont,NSForegroundColorAttributeName:txtColor,NSParagraphStyleAttributeName:styleCenter};
[txt drawInRect:rect withAttributes:attributes];
This category on NSString will draw the centered text in rect with given below font:
#implementation NSString (Helpers)
- (void)drawCentredInRect:(CGRect)rect withFont:(nullable UIFont *)font andForegroundColor:(nullable UIColor *)foregroundColor {
NSMutableDictionary *attributes = [NSMutableDictionary new];
if (font) {
attributes[NSFontAttributeName] = font;
}
if (foregroundColor) {
attributes[NSForegroundColorAttributeName] = foregroundColor;
}
CGSize textSize = [self sizeWithAttributes:attributes];
CGPoint drawPoint = CGPointMake(
CGRectGetMidX(rect) - (int) (textSize.width / 2),
CGRectGetMidY(rect) - (int) (textSize.height / 2)
);
[self drawAtPoint:drawPoint withAttributes:attributes];
}
I tried the answer for your clever question,Now I got the solution
+(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];
if([text respondsToSelector:#selector(drawInRect:withAttributes:)])
{
//iOS 7 or above iOS 7
NSMutableParagraphStyle *style = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
style.alignment = NSTextAlignmentCenter;
NSDictionary *attr = [NSDictionary dictionaryWithObject:style forKey:NSParagraphStyleAttributeName];
[text drawInRect:rect withAttributes:attr];
}
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
Please call the above method in where you pick the image like below
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
UIImage *imagePicked = info[UIImagePickerControllerEditedImage];
picker.delegate = self;
self.imageViewTextCenter.image = [ViewController drawText:#"WELCOME"
inImage:imagePicked
atPoint:CGPointMake(0, 0)];;
[picker dismissViewControllerAnimated:YES completion:nil];
}
I'm trying to draw text on a context, and it works.
I'm trying to set an UIfont to this text but it doesn't work. The text size remain the same.
Here my code
- (UIImage *)imageByDrawingCircleOnImage:(UIImage *)image
{
UIGraphicsBeginImageContextWithOptions((image.size), NO, [[UIScreen mainScreen]scale] );
[image drawAtPoint:CGPointZero];
CGContextRef context = UIGraphicsGetCurrentContext();
UIFont *font = [UIFont systemFontOfSize:30];;//[UIFont fontWithName: #"Helvetica" size:45.0];
CGContextSetRGBStrokeColor(context, 210.0/255.0f, 0.0f, 0.0f, 1.0f);
CGContextSetRGBFillColor(context, 192.0/255.0, 0.0/255.0 , 13.0/255.0, 1.0);
NSMutableParagraphStyle *textStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
textStyle.lineBreakMode = NSLineBreakByWordWrapping;
textStyle.alignment = NSTextAlignmentRight;
NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
[attributes setObject:textStyle forKey:#"NSParagraphStyleAttributeName"];
[attributes setObject:font forKey:#"NSFontAttributeName"];
NSString *string = #"Tour de poitrine : 95 cm";
CGSize string_len =[string sizeWithAttributes:attributes];
[string drawInRect:CGRectMake(245 - string_len.width, 100.0, string_len.width , 100) withAttributes:[NSDictionary dictionaryWithDictionary:attributes]];
UIImage *retImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return retImage;
}
Thanks
Alexandre
Do not use strings for your attributes dictionary keys, use the constants provided by the framework.
Replace #"NSFontAttributeName" by NSFontAttributeName and #"NSParagraphStyleAttributeName" by NSParagraphStyleAttributeName.
Replace your code by this. It's working for me.
- (UIImage *)imageByDrawingCircleOnImage:(UIImage *)image
{
UIGraphicsBeginImageContextWithOptions((image.size), NO, [[UIScreen mainScreen]scale] );
[image drawAtPoint:CGPointZero];
CGContextRef context = UIGraphicsGetCurrentContext();
UIFont *font = [UIFont fontWithName: #"Chalkduster" size:20.0];
CGContextSetRGBStrokeColor(context, 210.0/255.0f, 0.0f, 0.0f, 1.0f);
CGContextSetRGBFillColor(context, 192.0/255.0, 0.0/255.0 , 13.0/255.0, 1.0);
NSMutableParagraphStyle *textStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
textStyle.lineBreakMode = NSLineBreakByWordWrapping;
textStyle.alignment = NSTextAlignmentRight;
NSString *string = #"Tour de poitrine : 95 cm";
NSDictionary* attributes = #{NSFontAttributeName: font,
NSForegroundColorAttributeName: [UIColor redColor],
NSParagraphStyleAttributeName: textStyle
};
CGSize string_len =[string sizeWithAttributes:attributes];
[string drawInRect:CGRectMake(245 - string_len.width, 100.0, string_len.width , 100) withAttributes:[NSDictionary dictionaryWithDictionary:attributes]];
UIImage *retImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return retImage;
}
Try this:
//// General Declarations
CGContextRef context = UIGraphicsGetCurrentContext();
//// Text Drawing
CGRect textRect = CGRectMake(CGRectGetMinX(frame) + 23, CGRectGetMinY(frame) + 28, 101, 27);
{
NSString* textContent = #"Hello, World!";
NSMutableParagraphStyle* textStyle = NSMutableParagraphStyle.defaultParagraphStyle.mutableCopy;
textStyle.alignment = NSTextAlignmentLeft;
NSDictionary* textFontAttributes = #{NSFontAttributeName: [UIFont systemFontOfSize: UIFont.labelFontSize], NSForegroundColorAttributeName: UIColor.blackColor, NSParagraphStyleAttributeName: textStyle};
CGFloat textTextHeight = [textContent boundingRectWithSize: CGSizeMake(textRect.size.width, INFINITY) options: NSStringDrawingUsesLineFragmentOrigin attributes: textFontAttributes context: nil].size.height;
CGContextSaveGState(context);
CGContextClipToRect(context, textRect);
[textContent drawInRect: CGRectMake(CGRectGetMinX(textRect), CGRectGetMinY(textRect) + (CGRectGetHeight(textRect) - textTextHeight) / 2, CGRectGetWidth(textRect), textTextHeight) withAttributes: textFontAttributes];
CGContextRestoreGState(context);
}
I just want to know number of lines, given the font, constraints, and the text. Can I figure it out without creating a UILabel?
+ (int)numberOfLines:(NSDictionary *)data{
NSString *myString = [some string calculation];
CGSize sizeConstrain = CGSizeMake(some constrain calculation);
CGSize stringSize = [myString sizeWithFont:someFont constrainedToSize:sizeConstrain];
CGRect labelFrame = CGRectMake(0,
0,
stringSize.width,
stringSize.height + 2);
UILabel *label = [[UILabel alloc]initWithFrame:labelFrame];
label.text = myString;
return label.numberOfLines;
}
Yes
+ (int)numberOfLines:(NSDictionary *)data{
NSString *myString = [some string calculation];
CGSize sizeConstrain = CGSizeMake(some constrain calculation);
CGSize stringSize = [myString sizeWithFont:someFont constrainedToSize:sizeConstrain];
return (stringSize.height/someFont.lineHeight);
}
EDIT: I used this for UITextView and iOS7
- (CGFloat) getRowsForText:(NSString*) text{
CGFloat fixedWidth = 300;
UIFont *font = [UIFont fontWithName:#"HelveticaNeue" size:14];
NSMutableParagraphStyle *paragrapStyle = [[NSMutableParagraphStyle alloc] init];
paragrapStyle.alignment = NSTextAlignmentLeft;
textStepAttr = [NSDictionary dictionaryWithObjectsAndKeys:
font,NSFontAttributeName,
paragrapStyle, NSParagraphStyleAttributeName,
nil];
NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:text attributes:textStepAttr];
CGRect rect = [attributedText boundingRectWithSize:CGSizeMake(fixedWidth, MAXFLOAT)
options:NSStringDrawingUsesLineFragmentOrigin
context:nil];
return (rect.size.height / font.lineHeight) ;
}
im trying to first upload an image then write a text on it and after that save both items as one image.
im new in objective c so my code might be not the best way to get to my goal any help and suggestion wil help me.
thank you all
this is my code :
some how this editor is not allowing me to put my method declaration on
enter code here
UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
NSData *data = UIImagePNGRepresentation(image);
NSString *mijnImage =#"mijnImage.png";
NSArray *route = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES);
NSString *imageRoute = [route objectAtIndex:0];
NSString *routeNaarDeBestaand = [imageRoute stringByAppendingPathComponent:mijnImage];
[data writeToFile:routeNaarDeBestaand atomically:YES];
[[self imageView]setImage:image];
[self dismissViewControllerAnimated:YES completion:Nil];
self.imageView.image = [self drawText:#"Test String" inImage:image atPoint:CGPointMake(10, 20)];
this is another methode declaration same problem the editor is not allowing me to put it on
UIFont *font = [UIFont boldSystemFontOfSize:100];
UIGraphicsBeginImageContext(self.view.frame.size);
[originalImage drawInRect:CGRectMake(0,0,self.view.frame.size.width,self.view.frame.size.height)];
CGRect rect = CGRectMake(point.x, point.y,lblText.frame.size.width, lblText.frame.size.height);
rect.size = [text sizeWithAttributes:#{NSFontAttributeName:[UIFont systemFontOfSize:150.0f]}];
NSMutableDictionary *attributes = [[NSMutableDictionary alloc] init];
[attributes setObject:font forKey:NSFontAttributeName];
[attributes setObject:[NSNumber numberWithFloat:4] forKey:NSStrokeWidthAttributeName];
[attributes setObject:[UIColor whiteColor] forKey:NSStrokeColorAttributeName];
[text drawInRect:rect withAttributes:attributes];
[attributes removeObjectForKey:NSStrokeWidthAttributeName];
[attributes removeObjectForKey:NSStrokeColorAttributeName];
[attributes setObject:[UIColor blackColor] forKey:NSForegroundColorAttributeName];
[text drawInRect:rect withAttributes:attributes];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
I don't really know what problem is, but I did this.. let me know if it works for you
- (void)viewDidLoad
{
UIImage *image = [UIImage imageNamed:#"image"];
UIImage *newImage = [self image:image withText:#"Hello World" atPoint:CGPointMake(20, 20)];
[self saveImage:image withName:#"original"];
[self saveImage:newImage withName:#"new"];
}
- (UIImage*)image:(UIImage*)image withText:(NSString*)text atPoint:(CGPoint)point
{
CGRect rect = CGRectMake(0, 0, image.size.width, image.size.height);
UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0);
[image drawInRect:rect];
NSDictionary *attributes = #{NSFontAttributeName : [UIFont boldSystemFontOfSize:20],
NSStrokeWidthAttributeName : #(4),
NSStrokeColorAttributeName : [UIColor whiteColor]};
[text drawAtPoint:point withAttributes:attributes];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
- (void)saveImage:(UIImage*)image withName:(NSString*)name
{
NSString *documents = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents"];
NSString *imagePath = [documents stringByAppendingPathComponent:name];
[UIImagePNGRepresentation(image) writeToFile:imagePath atomically:YES];
}
Try this
+(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;
}
This answer will make the text both aligned vertically and horizontally in the center of the UIImage.
Note: not my answer it is collected from several answers
- (UIImage*)image:(UIImage*)image withText:(NSString*)text{
CGRect rect = CGRectMake(0, 0, image.size.width, image.size.height);
UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0);
[image drawInRect:rect];
/// Make a copy of the default paragraph style
NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
/// Set line break mode
paragraphStyle.lineBreakMode = NSLineBreakByTruncatingTail;
/// Set text horizontal alignment
paragraphStyle.alignment = NSTextAlignmentCenter;
NSDictionary *attributes = #{NSFontAttributeName : [UIFont boldSystemFontOfSize:16],
NSStrokeWidthAttributeName : #(4),
NSStrokeColorAttributeName : [UIColor whiteColor],
NSParagraphStyleAttributeName : paragraphStyle};
CGSize size = [text sizeWithAttributes:attributes];
CGRect newRect = CGRectMake(rect.origin.x,
rect.origin.y + (rect.size.height - size.height)/2.0,
rect.size.width,
size.height);
[text drawInRect:newRect withAttributes:attributes];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;}
I need a help with getting position of substring. I have enumerated substrings of UILabel, one randomly is changed to "aaaaa" and color to clear. I want to put UIImage in x,y of that string. I can easy get width and height of that string but I can't get origin.
Here is my code:
if (cloudWord !=nil)
{
[label.text enumerateSubstringsInRange:NSMakeRange(0, [label.text length]) options:NSStringEnumerationByWords usingBlock:^(NSString* word, NSRange wordRange, NSRange enclosingRange, BOOL* stop)
{
if ([word isEqualToString:#"aaaaa"])
{
NSLog(#"cloud");
[labelText addAttribute:NSForegroundColorAttributeName value:[UIColor clearColor] range:wordRange];
[label setAttributedText:labelText];
UIImageView *cloudImageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:#"playBtn.png"]];
[cloudImageView setFrame:CGRectMake(labelText.size.width, labelText.size.height, 40, 40)];
[self addSubview:cloudImageView];
}
}];
}
First find the range of your substring:
NSRange range = [myString rangeOfString:subString];
Then take the substring that precedes that range (from index 0 through the index before the first character of your substring) and find the width of that substring when rendered in the UILabel's font:
NSString *prefix = [myString substringToIndex:range.location];
CGSize size = [prefix sizeWithFont:[UIFont systemFontOfSize:fontSize]];
CGPoint p = CGPointMake(size.width, 0);
This will leave you with p as the (x,y) coordinate of the upper left corner of the substring within your UILabel. You may need to convert that to the coordinate system of your label's superview, depending on how you plan to display the image.
This assumes it's a 1-line UILabel. It gets much more complicated if your UILabel spans multiple lines...
If I am right You want to know the location of substring in your string, for that you can use this
NSRange range = [myString rangeOfString:subString options:NSBackwardsSearch range:yourRange];
NSLog(#"%u", range.loaction);
UPDATED:
You have to handle the cases for more than one line..
-(void)method
{
NSString *replaceString = #"aaaaa";
CGSize maximumLabelSize = CGSizeMake(200, FLT_MAX);
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, 30, 200, 20)];
NSString * string= #"1236587465987997970957986985090fhyjkhkk aaaaa 687439";
CGSize expectedLabelSize = [string sizeWithFont:label.font constrainedToSize:maximumLabelSize lineBreakMode:label.lineBreakMode];
CGRect newFrame = label.frame;
newFrame.size.height = expectedLabelSize.height;
label.frame = newFrame;
label.text = string;
label.backgroundColor = [UIColor redColor];
label.numberOfLines = 3;
[self.view addSubview:label];
NSRange range = [label.text rangeOfString:replaceString options:NSBackwardsSearch range:NSMakeRange(0, label.text.length)];
NSString *substring = [label.text substringWithRange:NSMakeRange(0, range.location)];
float stringWidth = [substring sizeWithFont:label.font].width;
float count =0;
float imgWidth = [replaceString sizeWithFont:label.font].width;
while( stringWidth> label.frame.size.width-5)
{
stringWidth = stringWidth - label.frame.size.width;
count++;
}
float imgX = stringWidth + label.frame.origin.x;
float imgHeight = 0;
float imgY = 0;
if (count >0) {
imgY = ((label.frame.size.height/(count+1))*count)+ label.frame.origin.y-10*count;
}
else
{
imgY = label.frame.origin.y;
imgHeight = [substring sizeWithFont:label.font].height;
if(stringWidth + imgWidth > label.frame.size.width)
{
imgX = label.frame.origin.x;
imgY = imgY + (label.frame.size.height/(count+1)) -10;
}
UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(imgX,imgY , imgWidth, imgHeight)];
imgView.image = [UIImage imageNamed:#"btn_Links.png"];
[self.view addSubview:imgView];
}
}