0

我正在尝试在 CGRect 的底部绘制一个 NSString。到目前为止,我已经能够将文本置于顶部居中,但我需要将其置于底部。我也尝试过 DrawAtPoint 但没有奏效。这是我目前拥有的代码: UIGraphicsBeginImageContext(img.size);

CGRect aRectangle = CGRectMake(0,0, img.size.width, img.size.height);
[img drawInRect:aRectangle];

[[UIColor whiteColor] set];
NSInteger fontSize = 25;
UIFont *font = [UIFont boldSystemFontOfSize: fontSize];

[text drawInRect:aRectangle withFont:font lineBreakMode:NSLineBreakByWordWrapping alignment:NSTextAlignmentCenter];



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

4

3 回答 3

0

可以使用方法: sizeWithFont:constrainedToSize:lineBreakMode 获取文本大小,然后计算左上点并使用drawAtPoint绘制文本

于 2012-09-19T02:54:00.247 回答
0

使用此方法:

 -(UIImage *)imageFromText:(NSString *)text
{
  CGSize maximumSize = CGSizeMake(300, 1000); //set width for string to wrap.
  UIFont *font = [UIFont boldSystemFontOfSize:16];
  CGSize strSize = [text sizeWithFont:font constrainedToSize:maximumSize lineBreakMode:UILineBreakModeWordWrap];
  if (UIGraphicsBeginImageContextWithOptions != NULL)
    UIGraphicsBeginImageContextWithOptions(strSize,NO,0.0);
  else
    // iOS is < 4.0 
    UIGraphicsBeginImageContext(strSize);

  CGRect newframe = CGRectMake(0, 0, strSize.width, strSize.height);
  [text  drawInRect:newframe 
                  withFont:font 
             lineBreakMode:UILineBreakModeWordWrap 
                 alignment:UITextAlignmentLeft]; 
  UIImage *testImg = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();    
  return testImg;
}
于 2012-09-19T04:16:12.350 回答
0

我发现这段代码对我的问题非常有帮助。

- (UIImage *)addText:(UIImage *)img text:(NSString *)text1{
    int w = img.size.width;
    int h = img.size.height;
    //lon = h - lon;
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef context = CGBitmapContextCreate(NULL, w, h, 8, 4 * w, colorSpace, kCGImageAlphaPremultipliedFirst);

    CGContextDrawImage(context, CGRectMake(0, 0, w, h), img.CGImage);
    CGContextSetRGBFillColor(context, 0.0, 0.0, 1.0, 1);

    char* text  = (char *)[text1 cStringUsingEncoding:NSASCIIStringEncoding];// "05/05/09";
    CGContextSelectFont(context, "Arial", 18, kCGEncodingMacRoman);
    CGContextSetTextDrawingMode(context, kCGTextFill);
    CGContextSetRGBFillColor(context, 255, 255, 255, 1);


    //rotate text
    CGContextShowTextAtPoint(context, 0, 5, text, strlen(text));


    CGImageRef imageMasked = CGBitmapContextCreateImage(context);
    CGContextRelease(context);
    CGColorSpaceRelease(colorSpace);

    return [UIImage imageWithCGImage:imageMasked];
}

于 2012-09-19T20:32:31.847 回答