2012-03-26 92 views
9

我想要在圖像上繪製單詞時應用圖像過濾器或蒙版。單詞將透明效果以透視背景圖像。 是否有可能在本地IOS sdk或我需要不同的api來執行此操作。 該圖片共有2張圖片。一個是印度寫過的地方,另一個是印度的信。 This image consist of 2 images. one is where India is written over, and another one is which is see through the India letter.如何在IOS sdk中掩蓋圖像?

這是我用來從文本生成圖像的代碼。

-(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;} 

它工作正常,但我需要生成的圖像將有黑色的背景和透明的文字來通過它。

+0

感謝你們。它正在工作。我們需要的2個圖像是掩蓋黑色背景和嵌入字母的圖像,另一個是掩蓋圖像的原始圖像。是否有可能從代碼中動態製作遮罩圖像? – arindam 2012-03-27 12:14:07

回答

13

您可以使用此代碼(從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]; 

} 
+0

這對Swift 4來說並不適用,我將原始圖像作爲蒙版圖像。 – iAviator 2017-08-03 06:14:43