比较两个UIImages Objective-c

时间:2016-12-02 13:00:05

标签: ios objective-c uibutton uiimage

我想从UIButton删除UIScrollView而不影响其他图片。

我遇到的问题是第一个请求删除最后一个图像(即使不是所选图像),然后任何后续请求都不会删除任何内容。

我开始只是做if(img == image),但没有产生匹配。然后在阅读this问题之后,我尝试了第二种方法(下面),但这会为匹配的图像生成两个不同的NSData结果。

这是我的代码:

-(void) deleteImage:(UIButton*)button{

        UIImage *image = [button imageForState:UIControlStateNormal];
        NSLog(@"image %@", image);
        for (NSArray *imageArr in self.imageArray) {
            NSString *filename = imageArr[0];
            UIImage *img = imageArr[1];
            if([self image:img isEqualTo:image]){

                RUN_ON_UI_THREAD(^{
                    [button removeFromSuperview];
                });
                double index = [self.imageArray indexOfObject:imageArr];
                [self.imageArray removeObjectAtIndex:index];
            }
            NSLog(@"img %@", img);



        }

       self.numberOfPhotosLabel.text = [NSString stringWithFormat:@"%lu",(unsigned long)[self.imageArray count]];

}

- (BOOL)image:(UIImage *)image1 isEqualTo:(UIImage *)image2{

    NSData *data1 = UIImagePNGRepresentation(image1);
    NSData *data2 = UIImagePNGRepresentation(image2);

    return [data1 isEqualToData:data2];
}
当用户按住deleteImage时,会调用

UIButton

viewDidLoad上,我浏览imageArray并使用以下内容将UIButton添加到屏幕:

-(void) addImageToScreen:(UIImage*) image;
{
int adjustHeight = 0;
int adjustWidth = 10;
int imagesInARow = 7;

int imageHeight = 75;
int imageWidth = 75;

int count = [self.imageArray count];
self.numberOfPhotosLabel.text = [NSString stringWithFormat:@"%i",count];

double index = 0;
if (count > 0) {
    for (NSArray *imageArr in self.imageArray) {
        UIImage *img = imageArr[1];
        if(image == img){
            index = [self.imageArray indexOfObject:imageArr];
        }
    }
}

if (count > 1 && count < imagesInARow) {
    adjustHeight = 0;
    adjustWidth = (20 * index) + (index * imageWidth);
}


UIButton* container = [[UIButton alloc] init ];

//create long press gesture recognizer(gestureHandler will be triggered after gesture is detected)
UILongPressGestureRecognizer* longPressGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(gestureHandler:)];
//adjust time interval(floating value CFTimeInterval in seconds)
[longPressGesture setMinimumPressDuration:1.0];
//add gesture to view you want to listen for it(note that if you want whole view to "listen" for gestures you should add gesture to self.view instead)


CGRect frame = CGRectMake(adjustWidth, 5, imageWidth, imageHeight);
NSLog(@"self.imageArr %lu", (unsigned long)[self.imageArray indexOfObject:image]);
[container setTag:[self.imageArray indexOfObject:image]];
[container setImage:image forState:UIControlStateNormal];
[container setFrame:frame];
[container addTarget:self action:@selector(displayFullScreenImage:) forControlEvents:UIControlEventTouchUpInside];
[container addGestureRecognizer:longPressGesture];
heldButton = container;
[self.photosView addSubview:container];


[self.view addSubview:self.photosView];

}

以下是我填充imageArray

的方法
-(void)buildImageArray{
[imageArray removeAllObjects];
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSArray* dirs = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsDirectory error:NULL];
[dirs enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    NSString *filename = (NSString *)obj;
    NSString *extension = [[filename pathExtension] lowercaseString];
    NSString *fileURL = [documentsDirectory stringByAppendingString: [@"/" stringByAppendingString:filename]];

    NSString *pack_id = [NSString stringWithFormat: @"%ld", (long)self.dataObject.pack_id];

    NSNumber *newNID = NID;
    if([NID integerValue] == -1 && [dict1 count] > 0){
        int noteID = [[dict1 valueForKey:@"noteID"] integerValue];
        newNID = [NSNumber numberWithInt: noteID - 1];
    }else if([NID integerValue] == -1){
        newNID = [NSNumber numberWithInt:[NID integerValue] - 1];
    }


    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    //self.signedInSwitch.on = true;

    NSString *username = [prefs objectForKey:@"username"];

    NSString *matchFileName = [NSString stringWithFormat:@"%@_%@_%@_notes_image", username, pack_id, newNID];

    if ([fileURL containsString:matchFileName]) {
        NSLog(@"filename %@", filename);
        UIImage *image = [UIImage imageWithContentsOfFile:fileURL];
        if(image != nil){
            NSMutableArray *subArray = [[NSMutableArray alloc] init];

            [subArray addObject:filename];
            [subArray addObject:image];

            [imageArray addObject:subArray];

        }

    }
}];
}

以下是比较图像时得到的响应:

    Selected Image <UIImage: 0x17428e5b0> size {4032, 3024} orientation 0 scale 1.000000 2016-12-02 13:26:38.517130 eCoss[2806:1722107] 
    Array Image 0 <UIImage: 0x17428e970> size {4032, 3024} orientation 0 scale 1.000000 2016-12-02 13:26:39.357693 eCoss[2806:1722107] 
    Selected Image <UIImage: 0x17428e790> size {4032, 3024} orientation 0 scale 1.000000 2016-12-02 13:26:39.357819 eCoss[2806:1722107] 
    Array Image 1 <UIImage: 0x17428e970> size {4032, 3024} orientation 0 scale 1.000000 2016-12-02 13:26:40.318356 eCoss[2806:1722107] 
    Selected Image <UIImage: 0x17428e970> size {4032, 3024} orientation 0 scale 1.000000 2016-12-02 13:26:40.318485 eCoss[2806:1722107]  
    Array Image 2 <UIImage: 0x17428e970> size {4032, 3024} orientation 0 scale 1.000000

3 个答案:

答案 0 :(得分:1)

对于此功能,比较图像数据会占用过多的处理器。相反,您可以在填充滚动视图时设置button.tag = [image_index]。

在您的操作中,您可以使用button.tag来识别单击的图像。

- (void)deleteImage:(UIButton*)button { 
    int clickedImageIndex = button.tag;
    ...
    [self.imageArray removeObjectAtIndex:clickedImageIndex];
    ...
}

答案 1 :(得分:0)

使用此示例代码:

2016-11-30 09:11:42.0

没有图像比较,我们可以这样做(使用按钮标签作为索引):

#import "ViewController.h"

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIButton *imageButton;

@property (strong, nonatomic) NSMutableArray *imageArray;

@property (strong, nonatomic) NSMutableArray *imageButtons;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    self.imageArray = [[NSMutableArray alloc]initWithCapacity:0];
    self.imageArray = [NSMutableArray arrayWithObjects:[UIImage imageNamed:@"bird.jpeg"],[UIImage imageNamed:@"panda.jpg"],[UIImage imageNamed:@"elephant.jpg"],[UIImage imageNamed:@"parrot.jpeg"],[UIImage imageNamed:@"kid.jpg"], nil];

    //Create five buttons and add to viewController

    for(int i=0; i<self.imageArray.count; i++)
    {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(20, 100 + i * 110, 100, 100);
        [button setImage:self.imageArray[i] forState:UIControlStateNormal];
        button.tag = i;
        [button addTarget:self action:@selector(deleteImageForButton:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:button];
        [self.imageButtons addObject:button];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (BOOL)image:(UIImage *)image1 isEqualTo:(UIImage *)image2{
    NSData *data1 = UIImagePNGRepresentation(image1);
    NSData *data2 = UIImagePNGRepresentation(image2);
    return [data1 isEqualToData:data2];
}

- (void)deleteImageForButton:(UIButton *)button{
    UIImage *image = [button imageForState:UIControlStateNormal];
    for (UIImage *presentImage in self.imageArray){
        if([self image:presentImage isEqualTo:image]){
            [button removeFromSuperview];
            double index = [self.imageArray indexOfObject:presentImage];
            [self.imageArray removeObjectAtIndex:index];
            break;
        }
    }
}

注意:用您自己的图像替换图像名称。

答案 2 :(得分:0)

一种方法是首先将它们转换为图像数据,然后进行比较。

- (BOOL)image:(UIImage *)image1 isEqualTo:(UIImage *)image2
{
    NSData *data1 = UIImagePNGRepresentation(image1);
    NSData *data2 = UIImagePNGRepresentation(image2);

    return [data1 isEqual:data2];
}

OR

- (BOOL)image:(UIImage *)aImage1 equalsTo:(UIImage *)aImage2
{
    NSData *img1Data = UIImageJPEGRepresentation(aImage1, 1.0);
    NSData *img2Data = UIImageJPEGRepresentation(aImage1, 1.0);
    return [img1Data isEqualToData:img2Data];
}

Swift实现@ Simon的回答:

func image(image1: UIImage, isEqualTo image2: UIImage) -> Bool {
    let data1: NSData = UIImagePNGRepresentation(image1)!
    let data2: NSData = UIImagePNGRepresentation(image2)!
    return data1.isEqual(data2)
}

或者根据@nhgrif的建议扩展UIImage:

import UIKit

extension UIImage {

    func isEqualToImage(image: UIImage) -> Bool {
        let data1: NSData = UIImagePNGRepresentation(self)!
        let data2: NSData = UIImagePNGRepresentation(image)!
        return data1.isEqual(data2)
    }
}