You have to use UIImageView in place of NSImageView.
Cannot set image in NSImageView
-
01-06-2022 - |
Question
I have a little piece of program to display an image in an Image-well. I've being testing around but there's nothing shows up on the screen. Appreciate any one can help.
.h file:
#import <Cocoa/Cocoa.h>
@interface TestAppDelegate : NSObject <NSApplicationDelegate>
{
IBOutlet NSImageView *myImageView;
}
@property (assign) IBOutlet NSWindow *window;
@property (assign) IBOutlet NSImageView *myImageView;
@end
.m file:
#import "TestAppDelegate.h"
@implementation TestAppDelegate
- (void)dealloc
{
[super dealloc];
}
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
NSString * filePath = @"haha.png"; // the pic file that I added into the project
NSImage * aImage = [NSImage imageNamed:filePath];
if(aImage)
{
NSLog(aImage.name);
NSLog(@"size %f %f",aImage.size.width,aImage.size.height);
//both of the NSLogs work but the Image-well shows blank
[myImageView setImage:aImage];
}
}
@end
Solution 4
OTHER TIPS
Replace
NSImage * aImage = [NSImage imageNamed:filePath]
to
NSImage * aImage = [[NSImage alloc] initWithContentsOfFile:filePath];
it might be that the png file's not found in the application's bundle. But the confusing thing is that both the NSlog functions ('NSLog(aImage.name) and NSLog(@"size %f %f",aImage.size.width,aImage.size.height)'). are working and feedbacking.
Here is how I added the png image. i created a new group folder called 'Resources', and then right clicked and added the prepared photo. Not sure if anything wrong i was doing here.
I finally figured it out. Just implly added a 'self' ahead to 'myImageView set Image:aImage'. like [self.myImageView setImage:aImage];
I had a similar issue too where I added an image to the Assets.xcassets
folder, but the image would not appear. The issue turned out to be a format issue, I had specified box.png
as the image was exported as a PNG
image. However my Mac app didn't recognise it (for whatever reason). So I removed the .png
from the string name:
[NSImage imageNamed:@"box"]
For some reason, the image I had made was not recognised as a PNG
image. It doesn't matter though, because as per the Apple dev docs, you don't need to specify the file format for PNG
images:
For PNG images, you may omit the filename extension. For all other file formats, always include the filename extension.