Search code examples
iosobjective-cuiviewdrawinrect

Can't set font for drawInRect


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


Solution

  • Do not use strings for your attributes dictionary keys, use the constants provided by the framework.

    Replace @"NSFontAttributeName" by NSFontAttributeName and @"NSParagraphStyleAttributeName" by NSParagraphStyleAttributeName.