adding NSImageView to NSScrollView - swift

I have an image with a dimension of about 200x2000 pixels. I want to display the image centered in a 200x200 rectangle but I want to be able to move it up and down. Best I can figure I need to add an NSImageView to an NSScrollView but I can't figure out how or even if this is the best way. This is my first day of OS X development...
After some googling I found this from which I was able to come up with this
class MasterViewController: NSViewController {
var Photo: NSImageView!
#IBOutlet var scroll: NSScrollView!
override func viewDidLoad() {
super.viewDidLoad()
var imageRect: NSRect
self.Photo = NSImageView.init()
self.Photo.image = NSImage.init(named:"horizon")
imageRect = NSMakeRect(0.0, 0.0, self.Photo.image!.size.width, self.Photo.image!.size.height)
print("image size", imageRect)
self.Photo = NSImageView(frame: imageRect)
self.Photo.setBoundsSize(NSSize(width: imageRect.width, height: imageRect.height))
self.Photo.imageScaling = NSImageScaling.ScaleNone
self.scroll.setFrameSize(NSSize(width: imageRect.width,height: imageRect.width))
self.scroll.hasVerticalScroller = true
self.scroll.hasHorizontalScroller = true
self.Photo.setFrameSize(CGSize(width: imageRect.width,height: imageRect.width))
self.scroll.documentView = self.Photo
//print(self.scroll.documentView?.frame)
//self.scroll.setC contentSize = NSSize(width: 200, height: 2000)
//self.Photo.image = NSImage.init(named:"bezel")
//self.scroll.addSubview(self.Photo)
}
but I can't get the image to show up inside the scrollview

#lusher00: in your example, you initialize twice self.Photo, first with an init() and then with (frame: imageRect), this probably explains why image don't show up.
You could set the imageView as the documentView of the NSScrollView, as below:
#IBOutlet var scrollView: NSScrollView!
var imageRect: NSRect
// Initialize below the imageView image with appropriate content (to adapt)
imageView.image = NSImage.init(named:"horizon")
imageRect = NSMakeRect(0.0, 0.0, imageView.image!.size.width, imageView.image!.size.height)
imageView.setFrameSize(CGSize(width: imageRect.width, height: imageRect.height))
imageView.imageScaling = NSImageScaling.ScaleNone
scrollView.documentView = imageView
scrollView.hasVerticalScroller = true
scrollView.hasHorizontalScroller = true

Just add the image view as a subview of the scrollview.
scrollView.addSubview(imageView)
You can set the position of the imageview, which will position it inside the scrollview.
The scrollview needs to know how large its content size is to enable scrolling of that area. So dont forget to update the contentSize property of the scrollview.
E.g. adding the imageView of 200x200 to the scrollView with a frame of 200x200. Setting the contentSize to 400x400 and calling imageView.center = scrollView.center, will center the image and allow some scrolling around the image, within the 200x200 visible frame of the scrollview.
You can also get the current offset of the scrollView by checking contentOffset.
If you need to track as the user scrolls, you can use scrollViewDidScroll. Check the docs for the scrollview for some other options.

Related

How do you move the uiimage inside the uiimageview to the right while retaining the aspect ratio of the original image?

I want to move an image to the right when a user imports it using uiimagepicker but when I set content mode = .right this occurs: The image enlarges for some reason and it looks like it moves to the left
Is there any way to keep the aspect ratio of the uiimageview and the aspect ratio of the imported image, and while also moving it to the right inside the image view.
This is how I want it to be
Here is one approach: custom view, using a sublayer with the content set to the image...
add a CALayer as a sublayer
calculate the aspect-scaled rectangle for the image inside the view's bounds
set the image layer's frame to that scaled rect
then set the layer's origin based on the desired alignment
A simple example:
class AspectAlignImageView: UIView {
enum AspectAlign {
case top, left, right, bottom, center
}
// this is an array so we can set two options
// if, for example, we don't know if the image will be
// taller or narrower
// for example:
// [.top, .right] will put a
// wide image aligned top
// narrow image aligned right
public var alignment: [AspectAlign] = [.center]
public var image: UIImage?
private let imgLayer: CALayer = CALayer()
override func layoutSubviews() {
super.layoutSubviews()
// make sure we have an image
if let img = image {
// only add the sublayer once
if imgLayer.superlayer == nil {
layer.addSublayer(imgLayer)
}
imgLayer.contentsGravity = .resize
imgLayer.contents = img.cgImage
// calculate the aspect-scaled rect inside our bounds
var scaledImageRect = CGRect.zero
let aspectWidth:CGFloat = bounds.width / img.size.width
let aspectHeight:CGFloat = bounds.height / img.size.height
let aspectRatio:CGFloat = min(aspectWidth, aspectHeight)
scaledImageRect.size.width = img.size.width * aspectRatio
scaledImageRect.size.height = img.size.height * aspectRatio
// set image layer frame to aspect-scaled rect
imgLayer.frame = scaledImageRect
// align as specified
if alignment.contains(.top) {
imgLayer.frame.origin.y = 0
}
if alignment.contains(.left) {
imgLayer.frame.origin.x = 0
}
if alignment.contains(.bottom) {
imgLayer.frame.origin.y = bounds.maxY - scaledImageRect.height
}
if alignment.contains(.right) {
imgLayer.frame.origin.x = bounds.maxX - scaledImageRect.width
}
}
}
}
class TestAlignViewController: UIViewController {
let testView = AspectAlignImageView()
override func viewDidLoad() {
super.viewDidLoad()
testView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(testView)
NSLayoutConstraint.activate([
// constrain test view 240x240 square
testView.widthAnchor.constraint(equalToConstant: 240.0),
testView.heightAnchor.constraint(equalTo: testView.widthAnchor),
// centered in view
testView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
testView.centerYAnchor.constraint(equalTo: view.centerYAnchor),
])
if let img = UIImage(named: "bottle") {
testView.image = img
}
testView.alignment = [.right]
// so we can see the actual view frame
testView.backgroundColor = .green
}
}
Using this image:
in a 240x240 view (view background set green so we can see its frame), we get this result:
Set your UIImage Content mode to aspect fill or aspect fit. Then use auto layout.

How to resize a NSTextView automatically as per its content?

I am making an app where a user can click anywhere on the window and a NSTextView is added programmatically at the mouse location. I have got it working with the below code but I want this NSTextView to horizontally expand until it reaches the edge of the screen and then grow vertically. It currently has a fixed width and when I add more characters, the text view grows vertically (as expected) but I also want it to grow horizontally. How can I achieve this?
I have tried setting isHorizontallyResizable and isVerticallyResizable to true but this doesn't work. After researching for a while, I came across this https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/TextStorageLayer/Tasks/TrackingSize.html but this didn't work for me either.
Code in my ViewController to add the NSTextView to its view:
private func addText(at point: NSPoint) {
let textView = MyTextView(frame: NSRect(origin: point, size: CGSize(width: 150.0, height: 40.0)))
view.addSubview(textView)
}
And, MyTextView class looks like below:
class MyTextView: NSTextView {
override func viewWillDraw() {
isHorizontallyResizable = true
isVerticallyResizable = true
isRichText = false
}
}
I have also seen this answer https://stackoverflow.com/a/54228147/1385441 but I am not fully sure how to implement it. I have added this code snippet in MyTextView and used it like:
override func didChangeText() {
frame.size = contentSize
}
However, I think I am using it incorrectly. Ergo, any help would be much appreciated.
I'm a bit puzzled, because you're adding NSTextView to a NSView which is part of the NSViewController and then you're talking about the screen width. Is this part of your Presentify - Screen Annotation application? If yes, you have a full screen overlay window and you can get the size from it (or from the view controller's view).
view.bounds.size // view controller's view size
view.window?.frame.size // window size
If not and you really need to know the screen size, check the NSWindow & NSScreen.
view.window?.screen?.frame.size // screen size
Growing NSTextView
There's no any window/view controller's view resizing behavior specified.
import Cocoa
class BorderedTextView: NSTextView {
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
let path = NSBezierPath(rect: bounds)
NSColor.red.setStroke()
path.stroke()
}
}
class ViewController: NSViewController {
override func mouseUp(with event: NSEvent) {
// Convert point to the view coordinates
let point = view.convert(event.locationInWindow, from: nil)
// Initial size
let size = CGSize(width: 100, height: 25)
// Maximum text view width
let maxWidth = view.bounds.size.width - point.x // <----
let textView = BorderedTextView(frame: NSRect(origin: point, size: size))
textView.insertionPointColor = .orange
textView.drawsBackground = false
textView.textColor = .white
textView.isRichText = false
textView.allowsUndo = false
textView.font = NSFont.systemFont(ofSize: 20.0)
textView.isVerticallyResizable = true
textView.isHorizontallyResizable = true
textView.textContainer?.widthTracksTextView = false
textView.textContainer?.heightTracksTextView = false
textView.textContainer?.size.width = maxWidth // <----
textView.maxSize = NSSize(width: maxWidth, height: 10000) // <----
view.addSubview(textView)
view.window?.makeFirstResponder(textView)
}
}
I finally got it to work (except for one minor thing). The link from Apple was the key here but they haven't described the code completely, unfortunately.
The below code work for me:
class MyTextView: NSTextView {
override func viewWillDraw() {
// for making the text view expand horizontally
textContainer?.heightTracksTextView = false
textContainer?.widthTracksTextView = false
textContainer?.size.width = 10000.0
maxSize = NSSize(width: 10000.0, height: 10000.0)
isHorizontallyResizable = true
isVerticallyResizable = true
isRichText = false
}
}
That one minor thing which I haven't been able to figure out yet is to limit expanding horizontally until the edge of the screen is reached. Right now it keeps on expanding even beyond the screen width and, in turn, the text is hidden after the screen width.
I think if I can somehow get the screen window width then I can replace 10000.0 with the screen width (minus the distance of text view from left edge) and I can limit the horizontal expansion until the edge of the screen. Having said that, keeping it 10000.0 won't impact performance as described in the Apple docs.

Image Slider using UIScrollView and Auto Layout

I am trying to implement a image slider using scrollView and pageControl, with the images being appended to the scrollView programmatically using the .addSubView method. The code is as follows:
#IBOutlet weak var sliderScrollView: UIScrollView!
#IBOutlet weak var sliderPageControl: UIPageControl!
var images: [String] = ["0", "1", "2"]
func updateSlider() {
sliderPageControl.numberOfPages = images.count
for index in 0..<images.count {
frame.origin.x = sliderScrollView.frame.size.width * CGFloat(index)
print(sliderScrollView.frame.size.width)
frame.size = sliderScrollView.frame.size
let image = UIImageView(frame: frame)
image.contentMode = .scaleAspectFill
image.image = UIImage(named: cafeObject.images[index])
sliderScrollView.addSubview(image)
}
sliderScrollView.contentSize = CGSize(width: sliderScrollView.frame.size.width * CGFloat(cafeObject.images.count), height: sliderScrollView.frame.size.height)
sliderScrollView.delegate = self
sliderPageControl.currentPage = 0
}
override func scrollViewDidScroll(_ scrollView: UIScrollView) {
let pageNumber = scrollView.contentOffset.x / scrollView.frame.size.width
switch scrollView {
case sliderScrollView:
sliderPageControl.currentPage = Int(pageNumber)
default:
break
}
}
As I designed the storyboard on iPhone 8 layout, the above code works nicely for iPhone 8. However, once I run the code in iPhone 8 Plus, the photo does not adapt the new size of the scrollView. I have added constraints to the scrollView such that the top, leading, trailing and bottom are equal to the super view's top, leading, trailing and bottom. When debugging, I realized that the UIImageView's frame is still using the old width as on iPhone 8.
Any workaround for this either programatically or using interface builder? Thanks!
Okay I managed to get this fixed by placing the updateSlider() function under viewDidLayoutSubviews() instead!

Zoom/Scroll through parts of image in a scrollview

I have an image which I divide into pages, such that each page shows a zoomed rectangle of the image. I think I should be able to do that with a UIImageView in a ScrollView, such that next page zooms the view to a given point. However I can't seem to get it to work.
This is the code for loading the image and setting the zoom on the first part (i.e. the first page) into scrollview:
scrollView.isPagingEnabled = true
scrollView.contentSize = CGSize(width: 1280, height: 1920)
scrollView.showsHorizontalScrollIndicator = false
scrollView.delegate = self as UIScrollViewDelegate
let image = UIImage(named: imageName)
let imageView = UIImageView(image: image!)
imageView.frame.origin.x = 0
scrollView.addSubview(imageView)
scrollView.zoom(toPoint: CGPoint(x:800,y:800), scale: 1, animated: false)
The image is obviously much larger than the size of the scrollview, which is 375/309.
I'm probably missing a lot here, or maybe there's a completely different way of achieving this.
the zoom function is borrowed from https://gist.github.com/TimOliver/71be0a8048af4bd86ede.
Thanks,
Z.
It seems like you'll want to set the content offset rather than zooming to a point. Try:
scrollView.contentOffset = CGPoint(x:800,y:800)

How to give an imageView in swift3.0.1 shadow at the same time with rounded corners

I want to give an imageView a shadow at the same time with rounded corners,but I failed.
Here is my solution
Basic idea :
Use an Extra view (say AView) as super view of image view (to those views on which you are willing to have shado) and assign that view class to DGShadoView
Pin Image view to AView (that super view)from left, right, top and bottom with constant 5
Set back ground color of the AView to clear color from storybosrd's Property inspector this is important
Inside idea: Here we are using a Bezier path on the Aview nearly on border and setting all rounded corner properties and shadow properties to that path and we are placing our target image view lie with in that path bound
#IBDesignable
class DGShadoView:UIView {
override func draw(_ rect: CGRect) {
self.rect = rect
decorate(rect: self.rect)
}
func decorate(rect:CGRect) {
//self.backgroundColor = UIColor.clear
//IMPORTANT: dont forgot to set bg color of your view to clear color from story board's property inspector
let ref = UIGraphicsGetCurrentContext()
let contentRect = rect.insetBy(dx: 5, dy: 5);
/*create the rounded oath and fill it*/
let roundedPath = UIBezierPath(roundedRect: contentRect, cornerRadius: 5)
ref!.setFillColor("your color for background".cgColor)
ref!.setShadow(offset: CGSize(width:0,height:0), blur: 5, color: "your color for shado".cgColor)
roundedPath.fill()
/*draw a subtle white line at the top of view*/
roundedPath.addClip()
ref!.setStrokeColor(UIColor.red.cgColor)
ref!.setBlendMode(CGBlendMode.overlay)
ref!.move(to: CGPoint(x:contentRect.minX,y:contentRect.minY+0.5))
ref!.addLine(to: CGPoint(x:contentRect.maxX,y:contentRect.minY+0.5))
}
}
Update
Extension Approach
There is another Approach. Just Make a class with empty and paste Following UIImageView Extension code, Assign this subclass to that ImageView on which you shadow.
import UIKit
class DGShadowView: UIImageView {
#IBInspectable var intensity:Float = 0.2{
didSet{
setShadow()
}
}
override func layoutSubviews()
{
super.layoutSubviews()
setShadow()
}
func setShadow(){
let shadowPath = UIBezierPath(rect: bounds)
layer.masksToBounds = false
layer.shadowColor = UIColor.black.cgColor
layer.shadowOffset = CGSize(width: 0.0, height: 0.3)
layer.shadowOpacity = intensity
layer.shadowPath = shadowPath.cgPath
}
}
The solution is to create two separate views. One for the shadow and one for the image itself. On the imageView you clipToBounds the layer so that the corner radius is properly added.
Put the imageView on top of the shadowView and you've got your solution!