【问题标题】:How to fill CGContext with UIImage?如何用 UIImage 填充 CGContext?
【发布时间】:2012-07-17 12:11:22
【问题描述】:

我继承UIView,我覆盖-drawRect:,我用CGContext绘制图形。现在我想用UIImage 填充这个数字。知道怎么做吗?

编辑:

我的代码来自-drawRect:

CGContextBeginPath(ctx);
//here I draw my figure
CGContextClosePath(ctx);
CGContextClip(ctx);

//this doesn't work
UIImage * image = [UIImage imageNamed:@"blackbackground.jgp"];
[image drawInRect:rect];

//this neither
CGImageRef cgImage = image.CGImage;
CGContextDrawImage(ctx, rect,  cgImage);

【问题讨论】:

  • 我认为需要更多细节。当您说“填充”时,您是指像在绘画程序中那样填充,还是您的意思是您只想将图像绘制到上下文中,还是需要用您的图形遮盖您的图像?
  • 我有一个圆形图形和一个矩形图像。首先,我需要拉伸图像以适合我的身材。其次,我想将角落成像为圆形,就像我的身材一样。你明白了吗,还是我不必要地复杂化了?

标签: objective-c ios xcode cgcontext


【解决方案1】:

将图像绘制到CGContext的正确方法是这样的:

UIImage *_originalImage = // your image

UIGraphicsBeginImageContext(_originalImage.size);
CGContextRef _context = UIGraphicsGetCurrentContext(); // here you don't need this reference for the context but if you want to use in the future for drawing anything else on the context you could get it for it
[_originalImage drawInRect:CGRectMake(0.f, 0.f, _originalImage.size.width, _originalImage.size.height)];

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

【讨论】:

    【解决方案2】:

    您需要使用图形路径剪辑上下文,然后绘制图像。看看这个答案,它解释了如何做第一部分How do I add a gradient to the text of a UILabel, but not the background?,一旦你剪辑了上下文,只需获取 UIImage 并调用其中一个绘图函数,如 drawInRect...

    【讨论】:

    • [image drawInRect:rect] 和 CGContextDrawImage(ctx,rect,cgImage) - 不起作用。查看我添加到问题中的代码。
    • 代码似乎没问题;您能否验证图像不是“空”,并尝试使用注释掉的图形剪辑来绘制图像,以查看图像 drawrect 是否有效?
    【解决方案3】:

    假设您的意思是要在图形“内部”绘制图像,最简单的方法是创建图形的 cgpath,确保路径已关闭,然后 CGContextClipToPath(context, path)

    添加

    我刚刚测试了您的代码,正如彼得所说,它应该可以工作。 我建议测试您的路径(设置笔触颜色和笔触路径),并尝试不使用蒙版的图像来找出问题所在。

    【讨论】:

    • 好的,我使用了 CGContextClip(context),现在如何在我的图形“内部”绘制图像?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-02
    • 2013-01-01
    • 1970-01-01
    • 2011-02-08
    • 1970-01-01
    • 2011-07-18
    • 1970-01-01
    相关资源
    最近更新 更多