如何在图像上下文中绘制图像和文本?

时间:2013-04-04 12:20:38

标签: iphone ios objective-c core-graphics

我试图在图像上绘制文字。当我不应用变换时,图像在左下角绘制,图像和文本很好(图2),但我希望图像在视图的左上角。

下面是我的drawRect实现。

如何翻转图像以使文本和图像正确对齐?

如何将图像移动到视图的左上角?

如果我不使用以下函数调用,则会在视图底部创建图像。(图2)

CGContextTranslateCTM(UIGraphicsGetCurrentContext(), 0.0, self.bounds.size.height);
CGContextScaleCTM(UIGraphicsGetCurrentContext(), 1.0, -1.0); 




 - (void)drawRect:(CGRect)rect
    {

         UIGraphicsBeginImageContext(self.bounds.size);

         // Fig 2 comment these lines to have Fig 2
         CGContextTranslateCTM(UIGraphicsGetCurrentContext(), 0.0, self.bounds.size.height);
         CGContextScaleCTM(UIGraphicsGetCurrentContext(), 1.0, -1.0);
        // Fig 2 Applying the above transformations results in Fig 1

         UIImage *natureImage = [UIImage imageNamed:@"Nature"];
         CGRect natureImageRect = CGRectMake(130, 380, 50, 50);
         [natureImage drawInRect:natureImageRect];


         UIFont *numberFont = [UIFont systemFontOfSize:28.0];
         NSFileManager *fm = [NSFileManager defaultManager];
         NSString * aNumber = @"111";
        [aNumber drawAtPoint:CGPointMake(100, 335) withFont:numberFont];    

        UIFont *textFont = [UIFont systemFontOfSize:22.0];
        NSString * aText = @"Hello";
        [aText drawAtPoint:CGPointMake(220, 370) withFont: textFont];
        self.image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();

        NSData * imageData = UIImagePNGRepresentation(self.image);
        NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"Image.png"];
        NSLog(@"filePath :%@", filePath);

        BOOL isFileCreated = [fm createFileAtPath:filePath contents:imageData attributes:nil];

        if(isFileCreated)
        {
            NSLog(@"File created at Path %@",filePath);
        }

    }

Flipped image when translation is applied

Image at the bottom left corner without translation

3 个答案:

答案 0 :(得分:0)

这是我用来绘制相同图像的代码(除了我没有使用自然图像)。它不在绘制矩形中,但根据你的最终目标,在自定义方法中在draw rect之外执行此操作可能会更好,并将self.image设置为 - (UIImage *)imageToDraw的结果。它输出:

You can tweak the frames to align stuff

以下是代码:

- (UIImage *)imageToDraw
{
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(320, 480), NO, [UIScreen mainScreen].scale);
    UIImage *natureImage = [UIImage imageNamed:@"testImage.png"];
    [natureImage drawInRect:CGRectMake(130, 380, 50, 50)];

    UIFont *numberFont = [UIFont systemFontOfSize:28.0];
    NSString * aNumber = @"111";
    [aNumber drawAtPoint:CGPointMake(100, 335) withFont:numberFont];

    UIFont *textFont = [UIFont systemFontOfSize:22.0];
    NSString * aText = @"Hello";
    [aText drawAtPoint:CGPointMake(220, 370) withFont:textFont];

    UIImage *resultingImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return resultingImage;
}

- (NSString *)filePath
{
    NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    return [documentsDirectory stringByAppendingPathComponent:@"Image.png"];
}

- (void)testImageWrite
{
    NSData *imageData = UIImagePNGRepresentation([self imageToDraw]);
    NSError *writeError = nil;
    BOOL success = [imageData writeToFile:[self filePath] options:0 error:&writeError];
    if (!success || writeError != nil)
    {
        NSLog(@"Error Writing: %@",writeError.description);
    }
}

无论如何 - 希望这有帮助

答案 1 :(得分:0)

您的图像参考框架是标准的iOS参考框架:原点位于左上角。相反,使用Core Text绘制的文本具有旧的参照系,原点位于左下角。只需对文本(而不是图形上下文)应用变换,如下所示:

CGContextSetTextMatrix(context, CGAffineTransformMakeScale(1.0f, -1.0f));

然后你的所有东西都会布局,好像轴的原点在左上角。

如果您必须使用Core Text编写整个句子而不仅仅是单词,请查看this blog post

答案 2 :(得分:0)

我想说drawRect方法用于在视图中绘制不创建图像。性能问题,drawInRect被称为很多。这个意图是更好的viewDidLoad或一些自定义方法。

我已根据您的要求做了一个示例:

- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.

UIGraphicsBeginImageContext(self.view.bounds.size);
CGContextRef context = UIGraphicsGetCurrentContext();

CGFloat margin = 10;

CGFloat y = self.view.bounds.size.height * 0.5;
CGFloat x = margin;
UIImage *natureImage = [UIImage imageNamed:@"image"];

CGRect natureImageRect = CGRectMake(x, y - 20, 40, 40);
[natureImage drawInRect:natureImageRect];
x += 40 + margin;

UIFont *textFont = [UIFont systemFontOfSize:22.0];
NSString * aText = @"Hello";

NSMutableParagraphStyle *style = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
style.alignment = NSTextAlignmentCenter;
NSDictionary *attr = @{NSParagraphStyleAttributeName: style,
                       NSFontAttributeName: textFont};

CGSize size = [aText sizeWithAttributes:attr];
[aText drawInRect: CGRectMake(x, y - size.height * 0.5, 100, 40)
         withFont: textFont
    lineBreakMode: UILineBreakModeClip
        alignment: UITextAlignmentLeft];

self.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

self.imageView.image = self.image;

}

enter image description here