【问题标题】:Drawing a PNG Image Into a Graphics Context for Blending Mode Manipulation将 PNG 图像绘制到图形上下文中以进行混合模式操作
【发布时间】:2010-12-28 13:01:32
【问题描述】:

我需要将一系列 PNG 绘制到 CGContext 中,以便将它们混合在一起:

CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetBlendMode(context, kCGBlendModeOverlay);

目前我的应用程序基于将每个图像绘制为 UIImageView 并将它们作为子视图添加到视图文件中,通过:[self addSubview:someImageView] ...但这不允许混合模式操作,对吗?

目前正在通过以下方式分配 UIImageView 变量:

someImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"image-name.png"]];

所以我尝试用其中任何一个替换它们,但没有成功:

[[UIImage imageNamed:@"image-name.png"] drawInRect:rect blendMode:kCGBlendModeOverlay alpha:1.0];

而这个需要一个CGImage,我不知道如何用 PNG 制作:

CGContextDrawImage(context, rect, someCGImage);

那么我错过了什么?这些不是由任何交互触发的,它们只需要在应用加载时加载/绘制。

感谢任何线索。 :)

【问题讨论】:

    标签: iphone cocoa-touch uiimage core-graphics quartz-graphics


    【解决方案1】:

    您不需要使用 UIImageViews。 相反,请将您的绘图置于对 UIGraphicsBeginImageContextUIGraphicsEndImageContext 的调用之间。

    例如(代码未尝试):

    UIImage* uiimage = [UIImage imageNamed:@"image-name.png"];
    UIImage* uiimage2 = [UIImage imageNamed:@"other-image-name.png"];
    
    CGSize size = uiimage.size; 
    
    UIGraphicsBeginImageContext(size);
    
    [uiimage drawAtPoint:CGPointZero blendMode:kCGBlendModeOverlay alpha:1.0];
    [uiimage2 drawAtPoint:CGPointZero blendMode:kCGBlendModeOverlay alpha:1.0];
    
    UIImage* blendedImage = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    

    如果要使用CG调用,调用:

    CGContextRef context = UIGraphicsGetCurrentContext();
    

    获取上下文参考。

    【讨论】:

    • 顺便说一句,从 UIImage 制作 CGImage 很容易。 UIImage 上有 CGImage 属性。但是,避免混合 UIImage 和 CGI​​mage 绘图例程,否则你会发现绘图上下文是颠倒的。
    • 我不清楚最后一部分,因为我想在绘制它们之前旋转 uiimages,但调用 CGContextRotateCTM(context, 3.14);在绘图命令实际上没有旋转所需的 180 度之前。是的,我在 drawRect 方法中调用的第一个命令是 CGContextRef context = UIGraphicsGetCurrentContext();想法?
    • 听起来你做得对。你能发布你的新代码吗?
    猜你喜欢
    • 1970-01-01
    • 2018-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多