[ios]更改图像使用如果语句

发布时间: 2017/3/21 23:30:16
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

我有安装燃料棒在我的游戏,但我想如果使用语句来更改栏如何低燃料百分比是基于图像。 出于某种原因,图像不改变所占比例。 因此,条依然是满的。 这里怎么一回事?

fuelRemaining = 100;
    FuelRemaining.text = [NSString stringWithFormat:@"%i%%", fuelRemaining];
    FuelBar.image = [UIImage imageNamed:@"fuel_bar_100.png"];
    if (fuelRemaining > 90) {
        FuelBar.image = [UIImage imageNamed:@"fuel_bar_100.png"];
    }
    else if (fuelRemaining > 80 && fuelRemaining <= 90) {
        FuelBar.image = [UIImage imageNamed:@"fuel_bar_90.png"];
    }
    else if (fuelRemaining > 70 && fuelRemaining <= 80) {
        FuelBar.image = [UIImage imageNamed:@"fuel_bar_80.png"];
    }
    else if (fuelRemaining > 60 && fuelRemaining <= 70) {
        FuelBar.image = [UIImage imageNamed:@"fuel_bar_70.png"];
    }
    else if (fuelRemaining > 50 && fuelRemaining <= 60) {
        FuelBar.image = [UIImage imageNamed:@"fuel_bar_60.png"];
    }
    else if (fuelRemaining > 40 && fuelRemaining <= 50) {
        FuelBar.image = [UIImage imageNamed:@"fuel_bar_50.png"];
    }
    else if (fuelRemaining > 30 && fuelRemaining <= 40) {
        FuelBar.image = [UIImage imageNamed:@"fuel_bar_40.png"];
    }
    else if (fuelRemaining > 20 && fuelRemaining <= 30) {
        FuelBar.image = [UIImage imageNamed:@"fuel_bar_30.png"];
    }
    else if (fuelRemaining > 10 && fuelRemaining <= 20) {
        FuelBar.image = [UIImage imageNamed:@"fuel_bar_20.png"];
    }
    else if (fuelRemaining > 0 && fuelRemaining <= 10) {
        FuelBar.image = [UIImage imageNamed:@"fuel_bar_10.png"];
    }
    else {
        FuelBar.image = [UIImage imageNamed:@"fuel_bar_0.png"];
    }

解决方法 1:

首先,简化,与一些基本数学函数︰

int fuelRounded = 10.0 * floor((fuelRemaining/10.0)+0.5);
NSString *fuelImageString = [NSString stringWithFormat:@"fuel_bar_%d.png", fuelRounded];
FuelBar.image = [UIImage imageNamed:fuelImageString];

(数学可能需要根据您的游戏逻辑和可能的值调整 fuelRemaining .)

第二,它看起来像你设置 fuelRemaining100 顶部的方法。您将需要设置后的图像再一次 fuelRemaining 已改为别的东西。

例如︰

- (void) updateFuelViews {
    FuelRemaining.text = [NSString stringWithFormat:@"%i%%", fuelRemaining];

    int fuelRounded = 10.0 * floor((fuelRemaining/10.0)+0.5);
    NSString *fuelImageString = [NSString stringWithFormat:@"fuel_bar_%d.png", fuelRounded];
    FuelBar.image = [UIImage imageNamed:fuelImageString];
}

然后调用 [self updateFuelViews]; 每次 fuelRemaining 的变化。

您可能希望研究键-值观察,这会让你自动更新燃料意见每当 fuelRemaining 变化。它是有点头痛,但能使它易于管理如果你有很多东西在不断变化。

赞助商