比较两个uiimages objective-c



我想从UIScrollView删除UIButton而不会影响其余图像。

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

我从简单地做if(img == image)开始,但这并没有产生匹配。然后,在阅读了此问题后,我尝试了第二种方法(下图),但为匹配图像产生了两个不同的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 S添加到屏幕:

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

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

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

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

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

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

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

@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)
    }
}

使用此示例代码:

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

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

- (void)deleteImageForButton:(UIButton *)button{
    [self.imageArray removeObjectAtIndex:button.tag];
    [button removeFromSuperview];
    for(long i=button.tag + 1; i<= self.imageArray.count ; i++)
    {
        UIButton *button = (UIButton *)[self.view viewWithTag:i];
        button.tag = button.tag - 1;
        [button setImage:self.imageArray[button.tag] forState:UIControlStateNormal];
    }
}

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

最新更新