我正在做一个小任务,通过TCP/IP接收文本字符串(json消息),其中一个条目包含一个灰度图像像素值的长列表,因此值在0-255之间。
NSString *foo = @"0,0,0,1,1,1,7,7,7,7,7,0,0,1,1,1,1,100,100,100,100,0,0,0,0,0,0,1,1,1";我想在我的UIImageView设备上显示这个字符串。我知道图像的宽度和高度( json消息的一部分),因此,例如,上面可以是宽度=6和高度= 5的图像,它将foo与30个条目(像素值)匹配。
我尝试对映像中的每一行使用for循环和NSRange迭代字符串(其中第一行的NSRange为0,5,下一行为6-11,等等),但我无法确定这是否是正确的方法,以及我应该将其转换为什么数据格式,例如NSData、NSArray或其他什么格式,以便能够将其用于UIImageView。
发布于 2013-09-26 07:27:00
试试这段代码。
NSString *foo = @"0,0,0,1,1,1,7,7,7,7,7,0,0,1,1,1,1,100,100,100,100,0,0,0,0,0,0,1,1,1";
NSArray *colors = [foo componentsSeparatedByString:@","];
int width = 6;
int height = 5;
//create drawing context
UIGraphicsBeginImageContextWithOptions(CGSizeMake(width, height), NO, 0.0f);
CGContextRef context = UIGraphicsGetCurrentContext();
//draw pixels
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
int index = x + y*width;
CGFloat val = [[colors objectAtIndex:index] floatValue];
val = val / 255.0f;
CGFloat components[4] = {val, val, val, 1.0f};
CGContextSetFillColor(context, components);
CGContextFillRect(context, CGRectMake(x, y, 1.0f, 1.0f));
}
}
//capture resultant image
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
CGRect frame = self.imageView.frame;
frame.size = CGSizeMake(width, height);
self.imageView.frame = frame;
self.imageView.image = image;https://stackoverflow.com/questions/19021080
复制相似问题