在iOS中向已加载的UIImage绘图

4

我有几个问题。

我有一张已加载的UIImage,我想要:

第一步 - 将另一张图片绘制到我的已加载的UIImage上

第二步 - 在我的已加载的UIImage上绘制一条线(带有颜色和粗细)

如果您能提供一些基本的东西,我将不胜感激,因为我还是一个新手:)


你的目标是什么?你想要一个包含所有绘制结果的新UIImage吗?还是你只是想在两个重叠的图像上显示一条线? - rmaddy
1个回答

3

还有另一种选择,它使用核心图形技术。

UIGraphicsBeginImageContextWithOptions(size, NO, 0.0);
CGContextRef context = UIGraphicsGetCurrentContext();

CGContextSaveGState(context);
UIImage *bottomImage = ...;
CGRect bottomImageRect = ...;
CGContextScaleCTM(context, 1.0, -1.0);
CGContextTranslateCTM(context, 0, -bottomImageRect.size.height);
CGContextDrawImage(context, bottomImageRect, bottomImage.CGImage);
CGContextRestoreGState(context);

CGContextSaveGState(context);
UIImage *topImage = ...;
CGRect topImageRect = ...;
CGContextScaleCTM(context, 1.0, -1.0);
CGContextTranslateCTM(context, 0, -topImageRect.size.height);
CGContextDrawImage(context, topImageRect, topImage.CGImage);
CGContextRestoreGState(context);

CGPoint origin = ...;
CGPoint end = ...;
CGContextMoveToPoint(context, origin.x, origin.y);
CGContextAddLineToPoint(context, end.x, end.y);
CGContextSetStrokeColorWithColor(context, [UIColor whatever].CGColor);
CGContextStrokePath(context);

UIImage *result = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();

编辑: 稍微修改了代码,使得图片不再翻转


我忘记了... 图像是用反转的坐标系绘制的。请查看编辑以获取修复。 - Ismael

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接