如何制作一个小的uiimage并手动设置像素?

时间:2011-04-14 06:08:27

标签: iphone objective-c uiimageview uiimage

对于投影,我想制作1px x 2px UIImage并手动将像素设置为某些RGBA值。

我该怎么做?我宁愿不用微小的png污染我的捆绑包。

谢谢!

3 个答案:

答案 0 :(得分:4)

这是一种方法。首先分配用RGB值填充的内存,然后调用'imageWithBytes'函数。

您分配的内存应为4 * width * height bytes。每个像素由四个字节描述,顺序为A,R,G,B。

完成后不要忘记释放记忆!

+ (UIImage*)imageWithBytes:(unsigned char*)data size:(CGSize)size
{
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    if (colorSpace == NULL)
    {
        NSLog(@"Could not create color space");
        return nil;
    }

    CGContextRef context = CGBitmapContextCreate(
        data, size.width, size.height, 8, size.width * 4, colorSpace,
        kCGImageAlphaPremultipliedFirst);

    CGColorSpaceRelease(colorSpace);

    if (context == NULL)
    {
        NSLog(@"Could not create context");
        return nil;
    }

    CGImageRef ref = CGBitmapContextCreateImage(context);
    if (ref == NULL)
    {
        NSLog(@"Could not create image");
        return nil;
    }

    CGContextRelease(context);

    UIImage* image = [UIImage imageWithCGImage:ref];
    CFRelease(ref);

    return image;   
}

答案 1 :(得分:1)

UIImage扩展程序:

extension UIImage {

    class func imageWithColor(color: UIColor, size: CGSize) -> UIImage {

        let rect = CGRect(origin: CGPoint.zeroPoint, size: size)

        UIGraphicsBeginImageContext(rect.size)

        let context = UIGraphicsGetCurrentContext()

        CGContextSetFillColorWithColor(context, color.CGColor)
        CGContextFillRect(context, rect)

        let image = UIGraphicsGetImageFromCurrentImageContext()

        UIGraphicsEndImageContext()

        return image

    }

}

答案 2 :(得分:-1)

UIImageView *imageView = [[UIImageView alloc] initWithFrame:yourFrame];
imageView.backgroundColor = [UIColor colorWithRed:redValue green:greenValue blue:blueValue alpha:alphaValue];
[self.view addSubview:imageView];
[imageView release];

希望这有帮助