比较图像背景

时间:2015-04-07 20:50:07

标签: objective-c xcode image compare

背景图片已经在Xcode项目中设置了,但是当点击按钮时它会改变,所以我想检查背景图像80red.png是否与按钮的背景相同刚点击。

-(IBAction)buttonChange:(id)sender {

    redImage = [UIImage imageNamed:@"80red.png”];

    UIImage *ButtonColour = [sender backgroundImageForState:UIControlStateNormal];       

    NSData *ButtonColourData = UIImagePNGRepresentation(ButtonColour);
    NSData *redImageData = UIImagePNGRepresentation(redImage);

    if ([ButtonColourData isEqual: redImageData]) {

        // if images are the same
        NSLog(@"Images are the same");    
    }    
}

我不明白为什么我的代码无效。

1 个答案:

答案 0 :(得分:0)

您的代码不起作用,因为您的代码语法有错误。

redImage不是对象UIImage类的链接 - 您必须编写UIImage *redImage = [UIImage imageNamed:@"80red.png"];

下一步:

当您对图像进行比较时,您需要比较图像的大小,但不同的图像可能大小相同。更好地比较其内容的图像。

我假装你的情况,这就是我得到的:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.


UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 2, 2)];
[button setBackgroundImage:[UIImage imageNamed:@"80red.png"] forState:UIControlStateNormal];

[self buttonChange:button];

return YES;

}

- (IBAction)buttonChange:(id)sender {

UIImage *redImage = [UIImage imageNamed:@"80red.png"];

UIImage *ButtonColour = [sender backgroundImageForState:UIControlStateNormal];

//NSData *ButtonColourData = UIImagePNGRepresentation(ButtonColour);
//NSData *redImageData = UIImagePNGRepresentation(redImage);

if ([redImage isEqual: ButtonColour]) {

    // if images are the same
    NSLog(@"Images are the same");

}

}

我希望我的建议能帮到你。

P.S。抱歉我的英文=)