UIImageView subclass duplicate image

I am working on subclassing UIImageView and one of the things I need is when the object is initialized with initWithImage: the message 'copy' appears.

I must be confusing something because I can't see what's not working here.

- (id)initWithImage:(UIImage *)image {
[image retain];
if (self = [super initWithImage:image]) {

    if (!maskImage) {
        maskImage = [UIImage imageWithCGImage:[image CGImage]];
        if (maskImage != nil) {
            NSLog(@"Made mask image");
        } else {
            NSLog(@"Failed");
        }
        //maskImage = [UIImage imageNamed:@"image.png"];
    }
}

[image release];
return self;
}

      

There are no errors creating this file and a masked image is generated (I am not getting an error). However, if I uncomment the line selection from png, it works.

What am I missing?

Thanks!

+1


a source to share


3 answers


You must save the created image, for example:



- (id)initWithImage:(UIImage *)image {
    if (self = [super initWithImage:image]) {
        if (!maskImage) {
                maskImage = [[UIImage imageWithCGImage:[image CGImage]] retain];
                if (maskImage != nil) {                
                        NSLog(@"Made mask image");
                } else {
                        NSLog(@"Failed");
                }
        }
    }
    return self;
}

      

+1


a source


Try it. It should work.

- (id)initWithImage:(NSString *)image {
if (self = [super initWithImage:image]) {

        if (!maskImage) {
                img = [UIImage imageNamed:image];
                maskImage = CGImageRetain(img.CGImage);
                if (maskImage != nil) {
                        NSLog(@"Made mask image");
                } else {
                        NSLog(@"Failed");
                }
        }
}

return self;
}

      



  • Changes
    • pass NSString instead of image
    • No need to save / free the image
    • need to define img, maskImage in .h
    • maskImage.h must have a save property in @property (e.g. @property (non-atomic, save))
0


a source


First, you must set maskImage to nil to make sure it's not garbage:

self.maskImage=nil;

      

This can mess up your line (if not now and then later):

if(!imaskImage)

      

Then, to make a copy, simply implement NSCopying in a UIImage subclass. It's easy to do. Then you can type:

maskImage = [image copy];

      

Alternatively, you can convert the image to data, archive, then decompress and then convert back to UIImage. This gives you a complete copy of the image. It's a little more complicated, but the same technique is used to create deep copies of the object graph.

0


a source







All Articles