簡體   English   中英

如何制作一個小的uiimage並手動設置像素?

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

對於投影,我想制作一個1px x 2px的UIImage並手動將像素設置為某些RGBA值。

我怎樣才能做到這一點? 我不想用小png污染我的捆綁包。

謝謝!

這是一種方法。 首先,您分配用RGB值填充的內存,然后調用“ imageWithBytes”函數。

您分配的內存應為4 *寬*高字節。 每個像素由四個字節描述,順序為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;   
}

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

    }

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

希望這可以幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM