Friday, October 22, 2021

#1 2021-07-18 08:35:11 am

Registered: 2019-10-23
Posts: 901

NSWindow, NSImage and NSImageView

I decided to update my library of useful building blocks (handlers) of AppKit.
The script could be run directly in Script Editor.

Choose a image to be displayed in NSWindow as NSImageView.


use framework "Foundation"
use framework "AppKit"
use scripting additions

set theImagePath to POSIX path of (choose file of type {"public.image"} default location (path to pictures folder))
its imageViewWithPath:theImagePath windowSize:{500, 700}

on imageViewWithPath:theImagePath windowSize:{theWidth, theHeight}
   set arguments to {imagePath:theImagePath, width:theWidth, height:theHeight}
   if my NSThread's isMainThread() as boolean then
       set arguments to current application's NSDictionary's dictionaryWithDictionary:arguments
       my performImageView:arguments
       my performSelectorOnMainThread:"performImageView:" withObject:arguments waitUntilDone:true
   end if
end imageViewWithPath:windowSize:

on performImageView:arguments
   set {width, height} to {arguments's valueForKey:"width", arguments's valueForKey:"height"}
   -- Initializes and returns an image object using the specified file.
   set theImageView to current application's NSImage's alloc()'s initWithContentsOfFile:(arguments's valueForKey:"imagePath")
   -- Create the image view.
   set theImageView to createImageView(0, 0, width, height, theImageView)
   -- Create the window.
   set theWindow to createWindowWithRect(0, 0, width, height)
   theWindow's contentView()'s addSubview:theImageView
   theWindow's setTitle:"Example with ImageView..."
   theWindow's |center|()
   theWindow's makeKeyAndOrderFront:me
end performImageView:

on createImageView(x, y, width, height, imageView)
   set imageViewSize to current application's NSMakeRect(x, y, width, height)
   set theImageView to current application's NSImageView's alloc()'s initWithFrame:imageViewSize
   theImageView's setImage:imageView
   return theImageView
end createImageView

on createWindowWithRect(x, y, width, height)
   set windowSize to current application's NSMakeRect(x, y, width, height)
   set winStyle to (current application's NSWindowStyleMaskTitled as integer) + (current application's NSWindowStyleMaskClosable as integer)
   set theWindow to current application's NSWindow's alloc()'s initWithContentRect:windowSize styleMask:winStyle backing:2 defer:true
   return theWindow
end createWindowWithRect

if you are the expert, who will you call if its not your imagination.



Board footer

Powered by FluxBB

RSS (new topics) RSS (active topics)