如何屏蔽UIImageView?

时间:2011-04-22 16:08:27

标签: ios objective-c uiimage mask

我试图用这样的东西掩盖图像:

image to be masked

你能帮帮我吗?

我正在使用此代码:

- (void) viewDidLoad {
    UIImage *OrigImage = [UIImage imageNamed:@"dogs.png"];
    UIImage *mask = [UIImage imageNamed:@"mask.png"];
    UIImage *maskedImage = [self maskImage:OrigImage withMask:mask];
    myUIIMage.image = maskedImage;
}

8 个答案:

答案 0 :(得分:159)

有一种更简单的方法。

#import <QuartzCore/QuartzCore.h>
// remember to include Framework as well

CALayer *mask = [CALayer layer];
mask.contents = (id)[[UIImage imageNamed:@"mask.png"] CGImage];
mask.frame = CGRectMake(0, 0, <img_width>, <img_height>);
yourImageView.layer.mask = mask;
yourImageView.layer.masksToBounds = YES;

对于Swift 4和plus,请按照以下代码

let mask = CALayer()
mask.contents =  [ UIImage(named: "right_challenge_bg")?.cgImage] as Any
mask.frame = CGRect(x: 0, y: 0, width: leftBGImage.frame.size.width, height: leftBGImage.frame.size.height)
leftBGImage.layer.mask = mask
leftBGImage.layer.masksToBounds = true

答案 1 :(得分:59)

本教程使用此方法时有两个参数:imagemaskImage,您必须在调用方法时设置这些参数。示例调用可能看起来像这样,假设方法在同一个类中,并且图片在您的包中:

注意 - 令人惊讶的是,图像甚至不必具有相同的尺寸。

...
UIImage *image = [UIImage imageNamed:@"dogs.png"];
UIImage *mask = [UIImage imageNamed:@"mask.png"];

// result of the masking method
UIImage *maskedImage = [self maskImage:image withMask:mask];

...

- (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 maskedImageRef = CGImageCreateWithMask([image CGImage], mask);
    UIImage *maskedImage = [UIImage imageWithCGImage:maskedImageRef];

    CGImageRelease(mask);
    CGImageRelease(maskedImageRef);

    // returns new image with mask applied
    return maskedImage;
}

在您提供代码后,我添加了一些数字作为评论以供参考。你还有两个选择。整个事情是一种方法,你在某处调用。您不需要在其中创建图像:这会将方法的可重用性降低到零。

让代码正常运行。将方法头( 1。)更改为

- (UIImage *)maskImageMyImages {

然后将 2。中变量的名称更改为

UIImage *maskImage = [UIImage imageNamed:@"mask.png"];

该方法将返回您的蒙版图像,因此您必须在某个地方调用此方法。 你能告诉我们你调用方法的代码吗?

答案 2 :(得分:12)

我使用CALayer或CGImageCreateWithMask尝试了两个代码,但没有一个对我不起作用

但我发现问题是png文件格式,而不是代码!!
所以只是为了分享我的发现!

如果你想使用

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

您必须使用 24位 png 不带 Alpha通道

如果你想使用CALayer蒙版,你必须使用(24位或8位)png alpha通道,其中png的透明部分将遮盖图像(对于平滑的渐变alpha蒙版...使用24bit png with alpha channel)

答案 3 :(得分:12)

Swift 3 - 我找到的最简单的解决方案

我为此创建了@IBDesignable,因此您可以立即在故事板上看到效果。

import UIKit

@IBDesignable
class UIImageViewWithMask: UIImageView {
    var maskImageView = UIImageView()

    @IBInspectable
    var maskImage: UIImage? {
        didSet {
            maskImageView.image = maskImage
            updateView()
        }
    }

    // This updates mask size when changing device orientation (portrait/landscape)
    override func layoutSubviews() {
        super.layoutSubviews()
        updateView()
    }

    func updateView() {
        if maskImageView.image != nil {
            maskImageView.frame = bounds
            mask = maskImageView
        }
    }
} 

如何使用

  1. 创建一个新文件并粘贴上面的代码。
  2. 将UIImageView添加到故事板(如果需要,可以指定图像)。
  3. 在Identity Inspector上:将自定义类更改为“UIImageViewWithMask”(上面的自定义类名称)。
  4. 在属性检查器上:选择遮罩图像 想用。
  5. 实施例

    Masking on Storyboard

    备注

    • 您的蒙版图像应具有非黑色部分的透明背景(PNG)。

答案 4 :(得分:10)

- (UIImage*) maskImage:(UIImage *)image withMask:(UIImage *)maskImage {
        CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();

        CGImageRef maskImageRef = [maskImage CGImage];

        // create a bitmap graphics context the size of the image
        CGContextRef mainViewContentContext = CGBitmapContextCreate (NULL, maskImage.size.width, maskImage.size.height, 8, 0, colorSpace, kCGImageAlphaPremultipliedLast);
        CGColorSpaceRelease(colorSpace);

        if (mainViewContentContext==NULL)
            return NULL;

        CGFloat ratio = 0;

        ratio = maskImage.size.width/ image.size.width;

        if(ratio * image.size.height < maskImage.size.height) {
            ratio = maskImage.size.height/ image.size.height;
        }

        CGRect rect1  = {{0, 0}, {maskImage.size.width, maskImage.size.height}};
        CGRect rect2  = {{-((image.size.width*ratio)-maskImage.size.width)/2 , -((image.size.height*ratio)-maskImage.size.height)/2}, {image.size.width*ratio, image.size.height*ratio}};


        CGContextClipToMask(mainViewContentContext, rect1, maskImageRef);
        CGContextDrawImage(mainViewContentContext, rect2, image.CGImage);


        // Create CGImageRef of the main view bitmap content, and then
        // release that bitmap context
        CGImageRef newImage = CGBitmapContextCreateImage(mainViewContentContext);
        CGContextRelease(mainViewContentContext);

        UIImage *theImage = [UIImage imageWithCGImage:newImage];

        CGImageRelease(newImage);

        // return the image
        return theImage;
}

这适合我。

答案 5 :(得分:8)

SWIFT 3 XCODE 8.1

func maskImage(image: UIImage, withMask maskImage: UIImage) -> UIImage {

    let maskRef = maskImage.cgImage

    let mask = CGImage(
        maskWidth: maskRef!.width,
        height: maskRef!.height,
        bitsPerComponent: maskRef!.bitsPerComponent,
        bitsPerPixel: maskRef!.bitsPerPixel,
        bytesPerRow: maskRef!.bytesPerRow,
        provider: maskRef!.dataProvider!,
        decode: nil,
        shouldInterpolate: false)

    let masked = image.cgImage!.masking(mask!)
    let maskedImage = UIImage(cgImage: masked!)

    // No need to release. Core Foundation objects are automatically memory managed.

    return maskedImage

}

// for use

testImage.image = maskImage(image: UIImage(named: "OriginalImage")!, withMask: UIImage(named: "maskImage")!)

答案 6 :(得分:3)

Swift版本的已接受解决方案:

func maskImage(image: UIImage, withMask maskImage: UIImage) -> UIImage {

    let maskRef = maskImage.CGImage

    let mask = CGImageMaskCreate(
        CGImageGetWidth(maskRef),
        CGImageGetHeight(maskRef),
        CGImageGetBitsPerComponent(maskRef),
        CGImageGetBitsPerPixel(maskRef),
        CGImageGetBytesPerRow(maskRef),
        CGImageGetDataProvider(maskRef),
        nil,
        false)

    let masked = CGImageCreateWithMask(image.CGImage, mask)
    let maskedImage = UIImage(CGImage: masked)!

    // No need to release. Core Foundation objects are automatically memory managed.

    return maskedImage

}

万一有人需要它。

它完美地为我工作。

答案 7 :(得分:2)

我们发现,正确的答案现在无法正常工作并实现了一个小插件类,这有助于屏蔽UIImageView中的任何图像。

可以在这里找到:https://github.com/Werbary/WBMaskedImageView

示例:

WBMaskedImageView *imgView = [[WBMaskedImageView alloc] initWithFrame:frame];
imgView.originalImage = [UIImage imageNamed:@"original_image.png"];
imgView.maskImage = [UIImage imageNamed:@"mask_image.png"];