开发者

How to make a small uiimage and manually set pixels on it?

For a drop shadow, i want to make a 1px x 2px UIImage and manually set the pixels to certain RGBA values.

How can i do this? I'd开发者_运维技巧 rather not pollute my bundle with tiny png's.

Thanks!


Here is a way to do it. First you allocate memory that you fill up with your RGB values, then you call the 'imageWithBytes' function.

The memory you allocate should be 4*width*height bytes. Every pixel is described by four bytes, in the order A,R,G,B.

Don't forget to free the memory when you're done!

+ (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;   
}


UIImage extension:

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

    }

}


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

Hope this helps

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜