字符串的特定颜色

时间:2014-05-03 09:33:52

标签: ios objective-c algorithm colors

我有一个uitableview,它来自网站的拉取数据,因此每个单元格都有一个新的字符串。为此,我希望根据单元格中的文本为用户显示HEX。

我已经尝试自己做到了,没有运气,但幸运的是找到了一个javascript脚本来完成我尝试做的事情。这个脚本,我现在需要转换为obj-c,我自己尝试过,但失败了。我希望得到一些帮助。

javascript:http://jsfiddle.net/sUK45/

我在obj-c中尝试(这里的字符串是基于来自网络的数据,但只是一个数组):

unichar hash = 0;

        NSArray *strings = [NSArray arrayWithObjects:@"MA", @"Ty", @"Ad", @"ER", nil];

        for (int i = 0; i < [[strings objectAtIndex:indexPath.row] length]; i++) {
            hash = [[strings objectAtIndex:indexPath.row] characterAtIndex:i] + ((hash < 5) - hash);
        }

        NSString *colour = @"#";
        for (int i = 0; i < 3; i++) {
            int value = (hash >> (i * 8)) & 0xFF;
            colour = [NSString stringWithFormat:@"%@%d", colour, value];
        }

        NSLog(@"%@", colour);

但我得到的数据,不是一个可用的HEX - NSlog:

#2432550
#3600
#3400
#1200

1 个答案:

答案 0 :(得分:1)

可能这不是唯一的错误。变化

hash = [[strings objectAtIndex:indexPath.row] characterAtIndex:i] + ((hash < 5) - hash);

hash = [[strings objectAtIndex:indexPath.row] characterAtIndex:i] + ((hash << 5) - hash);

更新:

同时更改

colour = [NSString stringWithFormat:@"%@%d", colour, value];

colour = [NSString stringWithFormat:@"%@%02x", colour, (unsigned int)value];

UPDATE2:

我已修复了一个错误和简化代码:

unsigned int hash = 0;

NSArray *strings = [NSArray arrayWithObjects:@"MA", @"Ty", @"Ad", @"ER", nil];
NSString *string = [strings objectAtIndex:indexPath.row];

for (int i = 0; i < string.length; i++) {
    hash = [string characterAtIndex:i] + ((hash << 5) - hash);
}

NSString *color = [NSString stringWithFormat:@"#%06x", hash % 0x1000000];
NSLog(@"%@", color);
相关问题