2012-03-26 14 views
9

Tôi muốn áp dụng bộ lọc hình ảnh hoặc mặt nạ khi một từ được vẽ trên hình ảnh. Từ đó sẽ có hiệu ứng trong suốt để xem qua hình nền. Có thể trong sdk iOS bản địa hoặc tôi cần api khác nhau để thực hiện điều này. Hình ảnh này bao gồm 2 hình ảnh. một là nơi Ấn Độ được viết trên, và một cái khác được xem qua bức thư Ấn Độ. This image consist of 2 images. one is where India is written over, and another one is which is see through the India letter.Làm thế nào để che giấu một hình ảnh trong sdk IOS?

Đây là mã tôi đang sử dụng để tạo hình ảnh từ văn bản.

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

Nó hoạt động tốt, tuy nhiên tôi cần tạo hình ảnh có nền đen và văn bản trong suốt để xem qua nó.

+0

cảm ơn các bạn. nó hoạt động. 2 hình ảnh tất cả chúng ta cần là một hình ảnh mặt nạ với nền đen và chữ nhúng và một hình ảnh khác là hình ảnh ban đầu mà mặt nạ sẽ làm việc. Có thể làm cho hình ảnh mặt nạ động từ mã? – arindam

Trả lời

13

Bạn có thể sử dụng mã này (nhận được từ 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

Điều này không hiệu quả đối với tôi trên Swift 4 và tôi nhận được hình ảnh gốc làm hình ảnh bị che khuất. – iAviator