简体   繁体   中英

How to create and store a new image file in cocoa

I want to create and store a empty white image file on the disk. As I am new to cocoa I don't know how to do it.

I see, your question is related to Mac as you have added cocoa and NSImage tags. So try this.

    NSRect kRect = NSMakeRect(0,0,100,100);
    NSView *view = [[NSView alloc] initWithFrame:kRect];

    CALayer *viewLayer = [CALayer layer];
    [viewLayer setBackgroundColor:CGColorCreateGenericRGB(1, 0.0, 0.0, 1)]; //RGB plus Alpha Channel
    [view setWantsLayer:YES]; // view's backing store is using a Core Animation Layer
    [view setLayer:viewLayer];

//    [self.window.contentView addSubview:view];

    NSBitmapImageRep* kRep = [view bitmapImageRepForCachingDisplayInRect:kRect];
    [view cacheDisplayInRect:kRect toBitmapImageRep:kRep];

    NSData* kData = [kRep representationUsingType:NSPNGFileType properties:nil];
    [kData writeToFile:@"/Users/MyName/Desktop/red.png" atomically:YES];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM