Unable to properly position NSImageView in NSView - macos

I would like to display an NSImageView in my main View:
img=[[NSImageView alloc]init];
[img setImage:[[NSImage alloc]initWithContentsOfFile:filename]];
width=img.image.size.width/2;
height=img.image.size.height/2;
[img setFrame:NSMakeRect(0,0,width ,height)];
mainview = [((AppDelegate *)[NSApp delegate]).window contentView];
[mainview addSubview:img];
The image is properly displayed, however instead of being in the top-left corner of my main window, it's completely going to the right side of the screen.
What is wrong above?

Try like this:-
- (void)windowDidLoad
{
NSString *imageName = [[NSBundle mainBundle] pathForResource:#"yourImage ofType:#"tiff"];
NSImage *photoImage = [[NSImage alloc] initWithContentsOfFile:imageName];
[yourimgView setImage:photoImage];
CGFloat width=yourimgView.bounds.size.width;
CGFloat height=yourimgView.bounds.size.height;
CGFloat xboundspoint=yourimgView.bounds.origin.x;
CGFloat yboundspoint=yourimgView.bounds.origin.y;
[yourimgView setFrame:NSMakeRect(xboundspoint, yboundspoint+150.0, width, height)];
[yourview addSubview:yourimgView];
[[[self window]contentView]addSubview:yourview];
[super windowDidLoad];
}

Related

Making an NSImage out of an NSView

I know how to create an NSImage depicting an NSView and all its subviews, but what I'm after is an NSImage of a view ignoring its subviews. I can think of ways of doing this with a subclass of NSView, but I'm keen to avoid subclassing if possible. Does anyone have any ideas?
Hide the subviews, grab the image, unhide the subviews:
NSMutableArray* hiddenViews = [[NSMutableArray] alloc init];
for (NSView* subview in [self subviews]) {
if (subview hidden) [hiddenViews addObject: subview];
else [subview setHidden:YES];
}
NSSize imgSize = self.bounds.size;
NSBitmapImageRep * bir = [self bitmapImageRepForCachingDisplayInRect:[self bounds]];
[bir setSize:imgSize];
[self cacheDisplayInRect:[self bounds] toBitmapImageRep:bir];
NSImage* image = [[NSImage alloc] initWithSize:imgSize];
[image addRepresentation:bir];
for (NSView* subview in [self subviews]) {
if (![hiddenViews containsObject: subview])
[subview setHidden:NO];
}
I would suggest making a copy of the desired NSView offscreen and taking a snapshot of that.

Create an animation like that of an NSPopOver

I'm working at a custom Window object that is displayed as child in a parent Window.
For this object I'd like to create an animation like that of an NSPopover.
My first idea is to create a Screenshot of the child Window, than animate it using Core Animation and finally showing the real Window.
Before begging the implementation I would like to know if exists a better method and what you think about my solution.
It's not trivial. Here's how I do it:
#interface ZoomWindow : NSWindow
{
CGFloat animationTimeMultiplier;
}
#property (nonatomic, readwrite, assign) CGFloat animationTimeMultiplier;
#end
#implementation ZoomWindow
#synthesize animationTimeMultiplier;
- (NSTimeInterval)animationResizeTime: (NSRect)newWindowFrame
{
float multiplier = animationTimeMultiplier;
if (([[NSApp currentEvent] modifierFlags] & NSShiftKeyMask) != 0) {
multiplier *= 10;
}
return [super animationResizeTime: newWindowFrame] * multiplier;
}
#end
#implementation NSWindow (PecuniaAdditions)
- (ZoomWindow*)createZoomWindowWithRect: (NSRect)rect
{
// Code mostly from http://www.noodlesoft.com/blog/2007/06/30/animation-in-the-time-of-tiger-part-1/
// Copyright 2007 Noodlesoft, L.L.C.. All rights reserved.
// The code is provided under the MIT license.
// The code has been extended to support layer-backed views. However, only the top view is
// considered here. The code might not produce the desired output if only a subview has its layer
// set. So better set it on the top view (which should cover most cases).
NSImageView *imageView;
NSImage *image;
NSRect frame;
BOOL isOneShot;
frame = [self frame];
isOneShot = [self isOneShot];
if (isOneShot) {
[self setOneShot: NO];
}
BOOL hasLayer = [[self contentView] wantsLayer];
if ([self windowNumber] <= 0) // <= 0 if hidden
{
// We need to temporarily switch off the backing layer of the content view or we get
// context errors on the second or following runs of this code.
[[self contentView] setWantsLayer: NO];
// Force window device. Kinda crufty but I don't see a visible flash
// when doing this. May be a timing thing wrt the vertical refresh.
[self orderBack: self];
[self orderOut: self];
[[self contentView] setWantsLayer: hasLayer];
}
// Capture the window into an off-screen bitmap.
image = [[NSImage alloc] initWithSize: frame.size];
[[self contentView] lockFocus];
NSBitmapImageRep* rep = [[NSBitmapImageRep alloc] initWithFocusedViewRect: NSMakeRect(0.0, 0.0, frame.size.width, frame.size.height)];
[[self contentView] unlockFocus];
[image addRepresentation: rep];
// If the content view is layer-backed the above initWithFocusedViewRect call won't get the content
// of the view (seems it doesn't work for CALayers). So we need a second call that captures the
// CALayer content and copies it over the captured image (compositing so the window frame and its content).
if (hasLayer)
{
NSRect contentFrame = [[self contentView] bounds];
int bitmapBytesPerRow = 4 * contentFrame.size.width;
CGColorSpaceRef colorSpace = CGColorSpaceCreateWithName(kCGColorSpaceSRGB);
CGContextRef context = CGBitmapContextCreate (NULL,
contentFrame.size.width,
contentFrame.size.height,
8,
bitmapBytesPerRow,
colorSpace,
kCGImageAlphaPremultipliedLast);
CGColorSpaceRelease(colorSpace);
[[[self contentView] layer] renderInContext: context];
CGImageRef img = CGBitmapContextCreateImage(context);
CFRelease(context);
NSImage *subImage = [[NSImage alloc] initWithCGImage: img size: contentFrame.size];
CFRelease(img);
[image lockFocus];
[subImage drawAtPoint: NSMakePoint(0, 0)
fromRect: NSMakeRect(0, 0, contentFrame.size.width, contentFrame.size.height)
operation: NSCompositeCopy
fraction: 1];
[image unlockFocus];
}
ZoomWindow *zoomWindow = [[ZoomWindow alloc] initWithContentRect: rect
styleMask: NSBorderlessWindowMask
backing: NSBackingStoreBuffered
defer: NO];
zoomWindow.animationTimeMultiplier = 0.3;
[zoomWindow setBackgroundColor: [NSColor colorWithDeviceWhite: 0.0 alpha: 0.0]];
[zoomWindow setHasShadow: [self hasShadow]];
[zoomWindow setLevel: [self level]];
[zoomWindow setOpaque: NO];
[zoomWindow setReleasedWhenClosed: NO];
[zoomWindow useOptimizedDrawing: YES];
imageView = [[NSImageView alloc] initWithFrame: [zoomWindow contentRectForFrameRect: frame]];
[imageView setImage: image];
[imageView setImageFrameStyle: NSImageFrameNone];
[imageView setImageScaling: NSScaleToFit];
[imageView setAutoresizingMask: NSViewWidthSizable | NSViewHeightSizable];
[zoomWindow setContentView: imageView];
[self setOneShot: isOneShot];
return zoomWindow;
}
- (void)fadeIn
{
[self setAlphaValue: 0.f];
[self orderFront: nil];
[NSAnimationContext beginGrouping];
[[NSAnimationContext currentContext] setDuration: 0.3];
[[self animator] setAlphaValue: 1.f];
[NSAnimationContext endGrouping];
}
- (void)zoomInWithOvershot: (NSRect)overshotFrame withFade: (BOOL)fade makeKey: (BOOL)makeKey
{
[self setAlphaValue: 0];
NSRect frame = [self frame];
ZoomWindow *zoomWindow = [self createZoomWindowWithRect: frame];
zoomWindow.alphaValue = 0;
[zoomWindow orderFront: self];
NSDictionary *windowResize = #{NSViewAnimationTargetKey: zoomWindow,
NSViewAnimationEndFrameKey: [NSValue valueWithRect: overshotFrame],
NSViewAnimationEffectKey: NSViewAnimationFadeInEffect};
NSArray *animations = #[windowResize];
NSViewAnimation *animation = [[NSViewAnimation alloc] initWithViewAnimations: animations];
[animation setAnimationBlockingMode: NSAnimationBlocking];
[animation setAnimationCurve: NSAnimationEaseIn];
[animation setDuration: 0.2];
[animation startAnimation];
zoomWindow.animationTimeMultiplier = 0.5;
[zoomWindow setFrame: frame display: YES animate: YES];
[self setAlphaValue: 1];
if (makeKey) {
[self makeKeyAndOrderFront: self];
} else {
[self orderFront: self];
}
[zoomWindow close];
}
This is implemented in an NSWindow category. So you can call:
- (void)zoomInWithOvershot: (NSRect)overshotFrame withFade: (BOOL)fade makeKey: (BOOL)makeKey
on any NSWindow.
I should add that I haven't been able to get both animations to run at the same time (fade and size), but the effect is quite similar to how NSPopover does it. Maybe someone else can fix the animation issue.
Needless to say this code works on 10.6 too where you don't have NSPopover (that's why I have written it in the first place).

NSProgressIndicator in NSStatusItem

I have NSStatusItem with a custom NSView which shows images.
Whether the menu is opened or not it show different images just like that:
isMenuVisible = NO;
- (void)awakeFromNib {
statusItem = [[NSStatusBar systemStatusBar] statusItemWithLength:NSVariableStatusItemLength];
[statusItem retain];
dragStatusView = [[DragStatusView alloc] init];
[dragStatusView retain];
dragStatusView.statusItem = statusItem;
[dragStatusView setMenu:statusMenu];
[dragStatusView setToolTip:NSLocalizedString(#"Menubar Countdown",
#"Status Item Tooltip")];
[statusItem setView:dragStatusView];
[dragStatusView setTitle:#"11"];
}
- (void)drawImage:(NSImage *)aImage centeredInRect:(NSRect)aRect{
NSRect imageRect = NSMakeRect((CGFloat)round(aRect.size.width*0.5f-aImage.size.width*0.5f),
(CGFloat)round(aRect.size.height*0.5f-aImage.size.height*0.5f),
aImage.size.width,
aImage.size.height);
[aImage drawInRect:imageRect fromRect:NSZeroRect operation:NSCompositeSourceOver fraction:1.0f];
}
- (void)drawRect:(NSRect)rect {
// Draw status bar background, highlighted if menu is showing
[statusItem drawStatusBarBackgroundInRect:[self bounds]
withHighlight:isMenuVisible];
if(isMenuVisible) {
[self drawImage:image2 centeredInRect:rect];
}else {
[self drawImage:image1 centeredInRect:rect];
}}
(Of course this is not everything, but i hope all the relevant code to understand my problem)
Now i want to show a NSProgressIndicator in this NSView (in this NSStatusItem) if an upload is proceeding which means
1. Set the NSProgressIndicator when upload starts
2.Received something ? ==> Hide NSProgressIndicator show the image again.
How would i solve this ?
Please help me. Thanks
Here is the solution for View based status item.
NSStatusBar *bar = [NSStatusBar systemStatusBar];
self.theItem = [bar statusItemWithLength:NSVariableStatusItemLength];
self.statusView = [[NSView alloc] initWithFrame:NSMakeRect(0, 0, 40, 20)];
NSProgressIndicator* progress = [[NSProgressIndicator alloc] initWithFrame:NSMakeRect(0, 0, 40, 20)];
[progress setIndeterminate:NO];
[self.statusView addSubview:progress];
self.theItem.view = self.statusView;
You can also draw a progress bar your self in Menu based status item
on progress change you can simply change the image of your status item.
- (void) updateIconWithProgress:(float)aProgress
{
NSImage* image = [NSImage imageNamed:#"small_icon_16_16.png"];
NSImage* img = [image copy];
[img lockFocus];
NSRect rect = NSMakeRect(2, 4, 12.0*aProgress, 8.0);
[[NSColor blueColor] set];
[NSBezierPath fillRect:rect];
[img unlockFocus];
[self.theItem setImage:img];
}
p.s. The code was written for ARC (Automatic Reference Counting) so there is no retain or release.

get the width and height of NSView and NSImageView

I have a NSView, there is a NSImageView on the NSView
in the source codes of the NSView
I wrote:
NSImage *image = [[[NSImage alloc] initWithContentsOfURL:url] autorelease];
NSImageView *newImageView = nil;
newImageView = [[NSImageView alloc] initWithFrame:[self bounds]];
[newImageView setImage:image];
[newImageView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
Is there a way to read the width and height of the NSView and NSImageView?
The size of any view (NSView, NSImageView, etc.) is view.frame.size or view.bounds.size.
In both cases it is an identical NSSize struct. You can write code like this:
NSSize size = newImageView.frame.size;
NSLog(#"size: %#", NSStringFromSize(size));
NSLog(#"size: %f x %f", size.width, size.height);
To change it, you need to update the view frame property:
NSRect frame = view.frame;
frame.size = NSMakeSize(<#new width#>, <#new height#>);
view.frame = frame;
Try the - (NSRect)bounds method.

NSString *text to NSString *icon?

I am making an app that is a standalone menu item and the basis for the code is sample code I found on a website. The sample code uses a number as the menu icon, but I want to change it to an image.
I want it to be like other apps where it shows icon.png when not clicked and icon-active.png when clicked.
The current code is this:
- (void)drawRect:(NSRect)rect {
// Draw background if appropriate.
if (clicked) {
[[NSColor selectedMenuItemColor] set];
NSRectFill(rect);
}
// Draw some text, just to show how it's done.
NSString *text = #"3"; // whatever you want
NSColor *textColor = [NSColor controlTextColor];
if (clicked) {
textColor = [NSColor selectedMenuItemTextColor];
}
NSFont *msgFont = [NSFont menuBarFontOfSize:15.0];
NSMutableParagraphStyle *paraStyle = [[NSMutableParagraphStyle alloc] init];
[paraStyle setParagraphStyle:[NSParagraphStyle defaultParagraphStyle]];
[paraStyle setAlignment:NSCenterTextAlignment];
[paraStyle setLineBreakMode:NSLineBreakByTruncatingTail];
NSMutableDictionary *msgAttrs = [NSMutableDictionary dictionaryWithObjectsAndKeys:
msgFont, NSFontAttributeName,
textColor, NSForegroundColorAttributeName,
paraStyle, NSParagraphStyleAttributeName,
nil];
[paraStyle release];
NSSize msgSize = [text sizeWithAttributes:msgAttrs];
NSRect msgRect = NSMakeRect(0, 0, msgSize.width, msgSize.height);
msgRect.origin.x = ([self frame].size.width - msgSize.width) / 2.0;
msgRect.origin.y = ([self frame].size.height - msgSize.height) / 2.0;
[text drawInRect:msgRect withAttributes:msgAttrs];
}
Also, I found a post describing a method on how to do this, but it did not work for me. The url to that is this: http://mattgemmell.com/2008/03/04/using-maattachedwindow-with-an-nsstatusitem/comment-page-1#comment-46501.
Thanks!
Use an NSImage and draw it where desired. For example:
NSString *name = clicked? #"icon-active" : #"icon";
NSImage *image = [NSImage imageNamed:name];
NSPoint p = [self bounds].origin;
[image drawAtPoint:p fromRect:NSZeroRect
operation:NSCompositeSourceOver fraction:1.0];
If this is for a status item and you just want an icon with no programmatic drawing, drop the view and set the status item's image and alternateImage. The former is what the status item uses normally; the status item switches to the alternate image (if it has one) when the user opens its menu.

Resources