UIImage in UIScrollView loads zoomed, rather than aspect fit - ios

I am using Xcode 6.4 and writing in swift.
Right now I am trying to display a simple image in aspect fit and then be able to zoom in. Unfortunately the image loads fully zoomed. Everything else works just fine, double tapping even results in seeing the image aspect fit. How could I change my code so that the image loads in aspect fit?
My case is very similar to
UIImage Is Not Fitting In UIScrollView At Start
However, the objective-c answer no longer works.
Here is my code for viewDidLoad
override func viewDidLoad() {
super.viewDidLoad()
imageView = UIImageView(image: UIImage(named: "image.png"))
scrollView = UIScrollView(frame: view.bounds)
scrollView.backgroundColor = UIColor.blackColor()
scrollView.contentSize = imageView.bounds.size
scrollView.autoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight
scrollView.contentOffset = CGPoint(x: 1000, y: 450)
scrollView.addSubview(imageView)
view.addSubview(scrollView)
scrollView.delegate = self
setZoomScale()
setupGestureRecognizer()
}
And here is my code for setZoomScale()
func setZoomScale() {
let imageViewSize = imageView.bounds.size
let scrollViewSize = scrollView.bounds.size
let widthScale = scrollViewSize.width / imageViewSize.width
let heightScale = scrollViewSize.height / imageViewSize.height
scrollView.minimumZoomScale = min(widthScale, heightScale)
scrollView.zoomScale = 1.0
}
All this originates from the online tutorial,
http://www.appcoda.com/uiscrollview-introduction/
Thank you in advance!

Solution, in my setZoomScale function, I set the scrollView's zoomscale to "1.0" rather than the minimum
here is the corrected code, hope this helps someone!
func setZoomScale() {
let imageViewSize = imageView.bounds.size
let scrollViewSize = scrollView.bounds.size
let widthScale = scrollViewSize.width / imageViewSize.width
let heightScale = scrollViewSize.height / imageViewSize.height
let minZoomScale = min(widthScale, heightScale)
scrollView.minimumZoomScale = minZoomScale
scrollView.zoomScale = minZoomScale
}

I tried the code in Stephen Mather's answer, but it did not work until I added this UIScrollView delegate method:
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return imageView
}

Related

Building a circular facepile of profile pictures in Swift: how to have the last photo tucked under the first?

I am trying to build a UIView that has a few UIImageViews arranged in a circular, overlapping manner (see image below). Let's say we have N images. Drawing out the first N - 1 is easy, just use sin/cos functions to arrange the centers of the UIImageViews around a circle. The problem is with the last image that seemingly has two z-index values! I know this is possible since kik messenger has similar group profile photos.
The best idea I have come up so far is taking the last image, split into something like "top half" and "bottom half" and assign different z-values for each. This seems doable when the image is the left-most one, but what happens if the image is the top most? In this case, I would need to split left and right instead of top and bottom.
Because of this problem, it's probably not top, left, or right, but more like a split across some imaginary axis from the center of the overall facepile through the center of the UIImageView. How would I do that?!
Below Code Will Layout UIImageView's in Circle
You would need to import SDWebImage and provide some image URLs to run the code below.
import Foundation
import UIKit
import SDWebImage
class EventDetailsFacepileView: UIView {
static let dimension: CGFloat = 66.0
static let radius: CGFloat = dimension / 1.68
private var profilePicViews: [UIImageView] = []
var profilePicURLs: [URL] = [] {
didSet {
updateView()
}
}
func updateView() {
self.profilePicViews = profilePicURLs.map({ (profilePic) -> UIImageView in
let imageView = UIImageView()
imageView.sd_setImage(with: profilePic)
imageView.roundImage(imageDimension: EventDetailsFacepileView.dimension, showsBorder: true)
imageView.sd_imageTransition = .fade
return imageView
})
self.profilePicViews.forEach { (imageView) in
self.addSubview(imageView)
}
self.setNeedsLayout()
self.layer.borderColor = UIColor.green.cgColor
self.layer.borderWidth = 2
}
override func layoutSubviews() {
super.layoutSubviews()
let xOffset: CGFloat = 0
let yOffset: CGFloat = 0
let center = CGPoint(x: self.bounds.size.width / 2, y: self.bounds.size.height / 2)
let radius: CGFloat = EventDetailsFacepileView.radius
let angleStep: CGFloat = 2 * CGFloat(Double.pi) / CGFloat(profilePicViews.count)
var count = 0
for profilePicView in profilePicViews {
let xPos = center.x + CGFloat(cosf(Float(angleStep) * Float(count))) * (radius - xOffset)
let yPos = center.y + CGFloat(sinf(Float(angleStep) * Float(count))) * (radius - yOffset)
profilePicView.frame = CGRect(origin: CGPoint(x: xPos, y: yPos),
size: CGSize(width: EventDetailsFacepileView.dimension, height: EventDetailsFacepileView.dimension))
count += 1
}
}
override func sizeThatFits(_ size: CGSize) -> CGSize {
let requiredSize = EventDetailsFacepileView.dimension + EventDetailsFacepileView.radius
return CGSize(width: requiredSize,
height: requiredSize)
}
}
I don't think you'll have much success trying to split images to get over/under z-indexes.
One approach is to use masks to make it appear that the image views are overlapped.
The general idea would be:
subclass UIImageView
in layoutSubviews()
apply cornerRadius to layer to make the image round
get a rect from the "overlapping view"
convert that rect to local coordinates
expand that rect by the desired width of the "outline"
get an oval path from that rect
combine it with a path from self
apply it as a mask layer
Here is an example....
I was not entirely sure what your sizing calculations were doing... trying to use your EventDetailsFacepileView as-is gave me small images in the lower-right corner of the view?
So, I modified your EventDetailsFacepileView in a couple ways:
uses local images named "pro1" through "pro5" (you should be able to replace with your SDWebImage)
uses auto-layout constraints instead of explicit frames
uses MyOverlapImageView class to handle the masking
Code - no #IBOutlet connections, so just set a blank view controller to OverlapTestViewController:
class OverlapTestViewController: UIViewController {
let facePileView = MyFacePileView()
override func viewDidLoad() {
super.viewDidLoad()
facePileView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(facePileView)
facePileView.dimension = 120
let sz = facePileView.sizeThatFits(.zero)
let g = view.safeAreaLayoutGuide
NSLayoutConstraint.activate([
facePileView.widthAnchor.constraint(equalToConstant: sz.width),
facePileView.heightAnchor.constraint(equalTo: facePileView.widthAnchor),
facePileView.centerXAnchor.constraint(equalTo: g.centerXAnchor),
facePileView.centerYAnchor.constraint(equalTo: g.centerYAnchor),
])
facePileView.profilePicNames = [
"pro1", "pro2", "pro3", "pro4", "pro5"
]
}
}
class MyFacePileView: UIView {
var dimension: CGFloat = 66.0
lazy var radius: CGFloat = dimension / 1.68
private var profilePicViews: [MyOverlapImageView] = []
var profilePicNames: [String] = [] {
didSet {
updateView()
}
}
func updateView() {
self.profilePicViews = profilePicNames.map({ (profilePic) -> MyOverlapImageView in
let imageView = MyOverlapImageView()
if let img = UIImage(named: profilePic) {
imageView.image = img
}
return imageView
})
// add MyOverlapImageViews to self
// and set width / height constraints
self.profilePicViews.forEach { (imageView) in
self.addSubview(imageView)
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.widthAnchor.constraint(equalToConstant: dimension).isActive = true
imageView.heightAnchor.constraint(equalTo: imageView.widthAnchor).isActive = true
}
// start at "12 o'clock"
var curAngle: CGFloat = .pi * 1.5
// angle increment
let incAngle: CGFloat = ( 360.0 / CGFloat(self.profilePicViews.count) ) * .pi / 180.0
// calculate position for each image view
// set center constraints
self.profilePicViews.forEach { imgView in
let xPos = cos(curAngle) * radius
let yPos = sin(curAngle) * radius
imgView.centerXAnchor.constraint(equalTo: centerXAnchor, constant: xPos).isActive = true
imgView.centerYAnchor.constraint(equalTo: centerYAnchor, constant: yPos).isActive = true
curAngle += incAngle
}
// set "overlapView" property for each image view
let n = self.profilePicViews.count
for i in (1..<n).reversed() {
self.profilePicViews[i].overlapView = self.profilePicViews[i-1]
}
self.profilePicViews[0].overlapView = self.profilePicViews[n - 1]
self.layer.borderColor = UIColor.green.cgColor
self.layer.borderWidth = 2
}
override func sizeThatFits(_ size: CGSize) -> CGSize {
let requiredSize = dimension * 2.0 + radius / 2.0
return CGSize(width: requiredSize,
height: requiredSize)
}
}
class MyOverlapImageView: UIImageView {
// reference to the view that is overlapping me
weak var overlapView: MyOverlapImageView?
// width of "outline"
var outlineWidth: CGFloat = 6
override func layoutSubviews() {
super.layoutSubviews()
// make image round
layer.cornerRadius = bounds.size.width * 0.5
layer.masksToBounds = true
let mask = CAShapeLayer()
if let v = overlapView {
// get bounds from overlapView
// converted to self
// inset by outlineWidth (negative numbers will make it grow)
let maskRect = v.convert(v.bounds, to: self).insetBy(dx: -outlineWidth, dy: -outlineWidth)
// oval path from mask rect
let path = UIBezierPath(ovalIn: maskRect)
// path from self bounds
let clipPath = UIBezierPath(rect: bounds)
// append paths
clipPath.append(path)
mask.path = clipPath.cgPath
mask.fillRule = .evenOdd
// apply mask
layer.mask = mask
}
}
}
Result:
(I grabbed random images by searching google for sample profile pictures)

Zoom and paging in one ScrollView

i am trying to create something like Photos gallery.
But now i have problem, with zooming in UIScrollView.
for i in 0..<imageArray.count{
let imageView = UIImageView()
imageView.isUserInteractionEnabled = true
imageView.image = imageArray[i]
imageView.contentMode = .scaleAspectFit
let xPosition = self.view.frame.width * CGFloat(i)
imageView.frame = CGRect(x: 0, y: 0, width: self.scrollView.frame.width, height: self.scrollView.frame.height)
scrollView.addSubview(imageView)
scrollView.contentSize.width = scrollView.frame.width * CGFloat(i+1)
}
scrollView.isScrollEnabled = true
scrollView.minimumZoomScale = 1.0
scrollView.maximumZoomScale = 6.0
scrollView.isUserInteractionEnabled = true
scrollView.delegate = self
Paging works fine, but i dont know now how to enable zooming each imageView.
You will need to implement the following method from the UIScrollViewDelegate protocol:
func viewForZooming(in: UIScrollView) -> UIView?
In that you return the view that you want to be zooming.
Now in this case you have multiple image views (depending on imageArray.count) but I assume you want to scroll into them all (i.e. not an individual image) so the best thing would be to add a 'content view' (UIView) to the scroll view and then add the individual image views to that instead of the scroll view directly and size it appropriately.
Then you can return that 'content view' in the viewForZooming method.
So assuming you have created this 'content view' then the method would look like this:
func viewForZooming(in: UIScrollView) -> UIView? {
return self.contentView
}

Decrease UILabel Font size to exact point using CGAffineTransform

I have a UITableView and a UINavigationBar with its custom title label. I want to decrease the title label font size on scroll down and increase it on scroll up.
Here is my code
override func viewDidLoad() {
super.viewDidLoad()
myLabel.font = UIFont(name: "Arial", size: 17)
}
Here I set the font size for my label.
And then, I transform the font size like so
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let offset = scrollView.contentOffset.y
let scale = min(max(1.0 - offset / 200.0, 0.0), 1.0)
myLabel.transform = CGAffineTransform(scaleX: scale, y: scale)
}
The problem is, the minimum point is set to 0 this way, but I want my label to decrease to 11 points, etc.
Can anyone help me edit my code?
calculate the final scale with this formula
let defualtFontSize = 17.0
let minFontSize = 11.0
let finalFontSize = CGFloat(minFontSize / defualtFontSize)
then use finalFontSize here
let scale = min(max(1.0 - offset / 200.0, finalFontSize), 1.0)
complete code
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let defualtFontSize = 17.0
let minFontSize = 11.0
let finalFontSize = CGFloat(minFontSize / defualtFontSize)
let offset = scrollView.contentOffset.y
let scale = min(max(1.0 - offset / 200.0, finalFontSize), 1.0)
myLabel.transform = CGAffineTransform(scaleX: scale, y: scale)
}
but write the calculation somewhere out of scrollViewDidScroll, avoiding CPU Usage.

ScrollView doesn't scroll in swift

I have an UIView and add an UIScrollView to it. Inside the scrollView is an UIImageView.
I want to zoom the image view by pressing a button. If the image view is zoomed you should be able to scroll but that's not working.
Currently I have that:
self.imageView = UIImageView()
self.imageView.image = image
self.imageView.frame = self.contentView.bounds
self.scrollView = UIScrollView()
self.scrollView.frame = self.contentView.bounds
self.scrollView.contentSize = self.contentView.bounds.size
self.scrollView.addSubview(self.imageView)
self.contentView.addSubview(self.scrollView)
and that:
#IBAction func zoomPicture() {
if (scale <= 1.5) {
scale = scale + 0.1
scrollView.transform = CGAffineTransformMakeScale(scale, scale)
scrollView.zoomScale = scale
scrollView.maximumZoomScale = 1.5
scrollView.minimumZoomScale = 1.0
scrollView.contentSize = contentView.bounds.size
scrollView.scrollEnabled = true
}
}
my class also implements UIScrollViewDelegateand I set the delegate in the viewDidLoad() function. I have also added the viewForZoomingInScrollView function. The zoom works but I can't scroll.
For this issue you have to set self.scrollView.contentSize bigger than self.contentView.bounds so it get proper space to scroll.
replace this line
self.scrollView.contentSize = self.contentView.bounds.size
to this:
self.scrollView.contentSize = self.contentView.bounds.size*2 //or what ever size you want to set
Try this:
#IBAction func zoomPicture() {
if (scale <= 1.5) {
scale = scale + 0.1
scrollView.zoomScale = scale
scrollView.maximumZoomScale = 1.5
scrollView.minimumZoomScale = 1.0
let size = contentView.bounds.size
scrollView.contentSize = CGSize(width: size.width * scale, height: size.height * scale)
scrollView.scrollEnabled = true
}
}

UIImageViews not scaling correctly in UIScrollView with paging

I'm trying to build a very simple UIScrollView with several images where paging is enabled.
However, I can't seen to get the images to correctly be resized to the bounds of my UIScrollView. The images are always bigger than the bounds, thus messing with my paging.
I have a UIScollView and a UIPageControl in Interface Builder and link it in my ViewController swift file.
Here is my viewDidLoad method (pageImages is defined as var pageImages: [UIImage] = [] and pageViews as var pageViews: [UIImageView?] = []:
override func viewDidLoad() {
scrollView.delegate = self
scrollView.pagingEnabled = true
scrollView.scrollEnabled = true
scrollView.showsHorizontalScrollIndicator = false
scrollView.showsVerticalScrollIndicator = false
scrollView.bounces = true
scrollView.scrollsToTop = false
pageImages = [UIImage(named: "image1")!,
UIImage(named: "image2")!,
UIImage(named: "image3")!,
UIImage(named: "image4")!,
UIImage(named: "image5")!]
let pageCount = pageImages.count
pageControl.currentPage = 0
pageControl.numberOfPages = pageCount
for (var i=0; i<pageCount; i++) {
var xOrigin: CGFloat = CGFloat(i) * scrollView.bounds.size.width
let imageView: UIImageView = UIImageView(frame: CGRectMake(xOrigin, 0, scrollView.bounds.size.width, scrollView.bounds.size.height))
imageView.image = pageImages[i]
imageView.contentMode = UIViewContentMode.ScaleAspectFill
imageView.clipsToBounds = true
scrollView.addSubview(imageView)
}
let pagesScrollViewSize = scrollView.frame.size
scrollView.contentSize = CGSize(width: pagesScrollViewSize.width * CGFloat(pageImages.count),
height: pagesScrollViewSize.height)
}
My scrollViewDidScroll method is as follows:
func scrollViewDidScroll(scrollView: UIScrollView) {
let pageWidth = self.scrollView.frame.size.width
let page = Int(floor((self.scrollView.contentOffset.x - pageWidth/2)/pageWidth) + 1)
self.pageControl.currentPage = page
}
Can anyone spot my mistake? Do I have to set the contentMode maybe in viewWillAppear or viewDidAppear?
Try setting up your imageViews sizes under:
(void)viewDidLayoutSubviews
At this point, autolayout had finished resizing your views/subviews according to the layout system you defined on interface builder so if your calculations are correct (according your requirements) this should work out fine.

Resources