L
L
Lici2015-04-01 19:22:44
Objective-C
Lici, 2015-04-01 19:22:44

How to create an image in Xcode + Swift?

As a result of the program, I get a picture in the form of a set of hexadecimal colors for each pixel. Type there #AABBCC #EEAA11 and so on for everyone. How to turn it into a picture? Is there some kind of library or standard function or method or something else? Didn't google anything on the road.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis, 2015-04-01
@denisk0n

"Food for thought" (c)
Blue rectangle, but only Xcode + Objective-C

#import <Foundation/Foundation.h>

int main(int argc, const char *argv[]) {
    const NSUInteger WIDTH = 100;
    const NSUInteger HEIGHT = 200;
    const NSUInteger COMPONENTS_PER_PIXEL = 4;
    const NSUInteger BITS_PER_COMPONENT = 8;
    const NSUInteger BUFFER_LENGTH = WIDTH * HEIGHT * COMPONENTS_PER_PIXEL;

    char *buffer = (char *) malloc(BUFFER_LENGTH);
    for (NSUInteger i = 0; i < BUFFER_LENGTH; i += 4) {
        buffer[i + 0] = 0x00;
        buffer[i + 1] = 0x00;
        buffer[i + 2] = 0xFF;
        buffer[i + 3] = 0xFF;
    }

    CGDataProviderRef dataProvider = CGDataProviderCreateWithData(NULL, buffer, BUFFER_LENGTH, NULL);
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGImageRef image = CGImageCreate(WIDTH, HEIGHT, BITS_PER_COMPONENT, BITS_PER_COMPONENT * COMPONENTS_PER_PIXEL, COMPONENTS_PER_PIXEL * WIDTH, colorSpace, kCGBitmapByteOrderDefault | kCGImageAlphaLast, dataProvider, NULL, false, kCGRenderingIntentDefault);

    NSString *filePath = @"~/test.png";
    NSURL *url = [NSURL fileURLWithPath:[filePath stringByExpandingTildeInPath]];
    CGImageDestinationRef imageDestination = CGImageDestinationCreateWithURL((__bridge CFURLRef) url, kUTTypePNG, 1, NULL);

    CGImageDestinationAddImage(imageDestination, image, NULL);

    CGImageDestinationFinalize(imageDestination);
    CGImageRelease(image);
    CGColorSpaceRelease(colorSpace);
    CGDataProviderRelease(dataProvider);
    free(buffer);

    return 0;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question