Display an Image in an Imageview in OS X Swift - xcode

I have a image view box and I want to display an image in it. I know how to do it without writing a line of code but I want to put an image in an image view with code. I've seen many examples online on how to do it in iOS, but I need to know how to do it in OS X. Any help would be appreciated.

Create NSImageView object
NSImageView has property 'image'.you can just assign to it.
Ex:
let imgView = NSImageView(frame:NSRect(x: 0, y: 0, width: 300, height: 300))
imgView.image = NSImage(named:"test")
self.view.addSubview(imgView)

Related

How to add a background image to a button in pygame gui?

I am trying to add an image as a background of a button in pygame gui. I have the button created now and I just need to add the image. How can I add the image to the button?
This is my code
game1 = pygame.Rect(150 , 100, 200, 150) # creates a rect object
pygame.draw.rect(screen, [255, 100, 0], game1) # draw objects down here
it works fine
You're probably looking for pygame.Surface.blit (http://www.pygame.org/docs/ref/surface.html#pygame.Surface.blit)
Load your background image and blit it wherever you want.
img = pygame.image.load('thisisanimage.png')
WhateverYourDisplayNameIs.blit(img,(x,y))
Just in case you're confused, it looks like you're using screen as your display surface.

Horizontal scrollView/UIImageView layout issue

The goal: Have a scroll view that displays an array of uiimageviews (photos) that you can horizontally scroll through them
How I understand to do this: Make the frame (CGRect) of each uiimageview the height and width of the scroll view, the y value to 0 on each, and set the first imgViews x value to 0. For every imgView after that, add the width of the scrollview to the x value. In theory, this would line the imgViews (Photos) up next to each other horizontally and not allow for any vertical scrolling or zooming, purely a horizontal photo viewer.
The storyboard setup: I am creating my scrollview in a xib file (It’s a custom uiCollectionViewCell), with these constraints:
— Top space to cell (0)
— Trailing space to cell (0)
— Leading space to cell (0)
— Height of 400
— Bottom space to a view (0)
—— (See Below for img)
Laying out the UIImgViews:
func layoutScrollView() {
for (index, img) in currentImages.enumerate() {
let imgView = UIImageView(frame: CGRect(x: CGFloat(index) * scrollView.bounds.width, y: CGFloat(0), width: scrollView.bounds.width, height: scrollView.bounds.height))
imgView.contentMode = .ScaleAspectFill
imgView.image = img
scrollView.addSubview(imgView)
scrollView.contentSize = CGSize(width: imgView.frame.width * CGFloat(index), height: scrollView.bounds.height)
scrollView.setNeedsLayout()
}
}
My suspicion: I suspect the issue is stemming from the auto layout constraints i’ve specified, but (considering Im asking a SO question) not sure
If there is a better way to do this (really the correct way) please let me know! I have been trying to wrap my head around this for a few days now.
I appreciate all responses! Thanks for reading
EDIT #1
I tried paulvs approach of setting setNeedsLayout & layoutIfNeeded before the "for" loop, and still no luck. Here is (out of three images selected) the second photo displaying. It seems that both the first and second photos are way longer than the content view and that would move the middle view over (Squished).
Your code looks fine except for a few details (that may be causing the problem):
Add:
view.setNeedsLayout()
view.layoutIfNeeded()
before accessing the scrollView's frame (a good place would be before the for-loop).
This is because when using Autolayout, if you access a view's frame before the layout engine has performed a pass, you will get incorrect frames sizes/positions.
Remove these lines from inside the for-loop:
scrollView.contentSize = CGSize(width: imgView.frame.width * CGFloat(index), height: scrollView.bounds.height)
scrollView.setNeedsLayout()
and place this line after (outside) the for loop:
scrollView.contentSize = CGSize(width: imgView.frame.width * CGFloat(currentImages.count), height: scrollView.bounds.height)

Creating a template image dynamically for OSX menu bar

I'm having trouble creating a template image for the OSX menu bar. As far as I can tell, it has to be a PDF image. To that end, I have:
var pageRect: CGRect = CGRectMake(0, 0, CGFloat(10), CGFloat(barHeight))
let pdfData: NSMutableData = CFDataCreateMutable(nil, 0)
let pdfConsumer = CGDataConsumerCreateWithCFData(pdfData as CFMutableDataRef)
let pdfContext = CGPDFContextCreate(pdfConsumer, &pageRect, nil)
Then I draw into the PDF:
CGPDFContextBeginPage(pdfContext, nil)
CGContextSetRGBFillColor (pdfContext, 1, 0, 0, 1)
CGContextFillRect (pdfContext, CGRectMake (0, 0, 200, 100 ))
CGPDFContextEndPage(pdfContext)
Then I try to create an NSImage:
let image = NSImage(data: pdfData)
And add it to the status item's image property:
button.image = image
However, this just isn't working. I have tried saving the image to disk and opening it, but get the message that the image is corrupted, so I suspect the error is in converting the pdfData into an NSImage, though I'm not totally confident of that. Anyway, any help would be appreciated.
A template image does not have to be a PDF. To make an instance of NSImage a template image, simply set its template property to true.
No matter the nature of the image (bitmap, PDF, whatever), the system will only make use of its alpha channel when it's a template image. The color channels are ignored.
The system will automatically mark an image loaded from a file as a template image if its filename-minus-extension ends with "Template". So, for example, fooTemplate.png or barTemplate.pdf.

How to make button with image and determine CGSize in sprite kit swift

How can I create a button with an image so I can still decided the CGSize myself. Right now I can only do this.
let playNode = SKSpriteNode(color: SKColor.redColor(), size: CGSize(width: 100, height: 44))
playNode.position = CGPoint(x:CGRectGetMidX(self.frame), y:CGRectGetMidY(self.frame));
playNode.name = "play"
addChild(playNode)
I would like to replace the red color with an actual image. So far I haven't found a way how to actual create a button with an image AND decide its CGSize. I do know how to create a button just with an image, but I can't determine its CGSize then. Any help would be appreciated !
You can set the size property of your node after you've set the image. Like that:
let playNode = SKSpriteNode(imageNamed: "yourImage")
//Set it after you've set the image.
playNode.size = CGSizeMake(200, 200)
playNode.position = CGPoint(x:CGRectGetMidX(self.frame), y:CGRectGetMidY(self.frame))
playNode.name = "play"
addChild(playNode)

How to resize NSTextField when content increase in NSTextField

i have NSTextField but content that i have to show is not fixed , it will grow dynamically.
is there any way in simple way through which we can change size dynamically.
Thanks in Advance :)
The text field's delegate needs to update the size as the text changes.
The trick is you have to manually update the stringValue property, to avoid bugs:
override func controlTextDidChange(obj: NSNotification) {
guard let field = obj.object as? NSTextField else {
return
}
// re-apply the string value, this is necessary for the text field to correctly calculate it's width
field.stringValue = field.stringValue
// calculate the new dimensions
let maxWidth: CGFloat = 500
let maxHeight: CGFloat = 50
let size = renameField.sizeThatFits(NSSize(width: maxWidth, height: maxHeight))
// apply them
field.frame = NSRect(x: field.frame.origin.x, y: field.frame.origin.y, width: size.width, height: size.height)
}
If you're just showing content, as opposed to typing in the text field, then you should use a label, which can be set in IB to "Size To Fit Content". This will cause the label to be just big enough for the content.
There is no option to set through Interface Builder.
However you can do through codes:
You can set a delegate on the NSTextField which implements
- (void)controlTextDidChange:(NSNotification *)aNotification;
Every time the delegate gets called resize the control per your idea above.
Also, this one.
There is a great category on NSString/NSAttributedString by Jerry Krinock which allows you to calculate the height of text based on its width and vice versa:
http://www.sheepsystems.com/sourceCode/sourceStringGeometrics.html
Edit March 2016 :
Now as Autolayout feature is there for Mac OS applications that helps to increase and decrease the size of textfield and even NSWindow, so you can use them it very easy to use. Just put constraints from either side of the Window, and set the constraints something as ( >= desiredMinimumSize ) and you are done!

Resources