【问题标题】:How to mask an image in IOS sdk?如何在 IOS sdk 中屏蔽图像?
【发布时间】:2012-04-10 00:09:40
【问题描述】:

我想在图像上绘制单词时应用图像过滤器或蒙版。该单词将具有透明效果以看穿背景图像。 是否可以在本机 IOS sdk 中使用,或者我需要不同的 api 来执行此操作。 此图像由 2 个图像组成。一个是写印度的地方,另一个是看穿印度信的地方。

这是我用来从文本生成图像的代码。

-(UIImage *)imageFromText:(NSString *)text{
// set the font type and size
UIFont *font = [UIFont systemFontOfSize:100.0];  
CGSize size  = [text sizeWithFont:font];

// check if UIGraphicsBeginImageContextWithOptions is available (iOS is 4.0+)
if (UIGraphicsBeginImageContextWithOptions != NULL)
    UIGraphicsBeginImageContextWithOptions(size,NO,0.0);
else
    // iOS is < 4.0 
    UIGraphicsBeginImageContext(size);

// optional: add a shadow, to avoid clipping the shadow you should make the context size bigger 
//
 CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextSetShadowWithColor(ctx, CGSizeMake(0.0, 1.0), 5.0, [[UIColor blackColor] CGColor]);
CGContextSetBlendMode(ctx,kCGBlendModeNormal);
CGContextSetFillColorWithColor(ctx, [UIColor whiteColor].CGColor);


/*NSLog(@"Rect  %@",CGContextGetClipBoundingBox(ctx));
CGImageRef alphaMask = CGBitmapContextCreateImage(ctx);
CGContextClipToMask(ctx, CGContextGetClipBoundingBox(ctx), alphaMask);*/


// draw in context, you can use also drawInRect:withFont:
[text drawAtPoint:CGPointMake(0.0, 0.0) withFont:font];

// transfer image
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();    

return image;}

它工作正常,但是我需要生成具有黑色背景和透明文本的图像才能看穿它。

【问题讨论】:

  • 谢谢你们。它正在工作。 2张图片我们只需要一张是带有黑色背景和嵌入字母的遮罩图像,另一张是可以使用遮罩的原始图像。是否可以从代码中动态制作遮罩图像?

标签: iphone ios image-processing uiimage


【解决方案1】:

您可以使用此代码(来自here),

- (UIImage*) maskImage:(UIImage *)image withMask:(UIImage *)maskImage {

    CGImageRef maskRef = maskImage.CGImage; 

    CGImageRef mask = CGImageMaskCreate(CGImageGetWidth(maskRef),
        CGImageGetHeight(maskRef),
        CGImageGetBitsPerComponent(maskRef),
        CGImageGetBitsPerPixel(maskRef),
        CGImageGetBytesPerRow(maskRef),
        CGImageGetDataProvider(maskRef), NULL, false);

    CGImageRef masked = CGImageCreateWithMask([image CGImage], mask);
    return [UIImage imageWithCGImage:masked];

}

【讨论】:

  • 这在 Swift 4 上对我不起作用,我将原始图像作为蒙版图像。
猜你喜欢
  • 2014-11-17
  • 1970-01-01
  • 2011-06-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-06
  • 2011-02-19
  • 1970-01-01
相关资源
最近更新 更多