I'm creating a wallpaper app for iOS. I've created a UIImageView, but am stuck on saving the image. I have solved the permissions but am unable to have the user save the image. I created the save button itself, but I don't know to make save any image from the image array in the user's image gallery.
Here is my code so far:
class ViewController: UIViewController {
#IBOutlet var imageview: [UIScrollView]!
#IBOutlet weak var saveButton: UIButton!
#IBAction func saveButtonPressed(_ sender: UIButton) {
// TODO: - How to save the image here
}
let scrollView: UIScrollView = {
let scroll = UIScrollView()
scroll.isPagingEnabled = true
scroll.showsVerticalScrollIndicator = false
scroll.showsHorizontalScrollIndicator = false
scroll.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)
return scroll
}()
var imageArray = [UIImage]()
func setupImages(_ images: [UIImage]){
for i in 0..<images.count {
let imageView = UIImageView()
imageView.image = images[i]
let xPosition = UIScreen.main.bounds.width * CGFloat(i)
imageView.frame = CGRect(x: xPosition, y: 0, width: scrollView.frame.width, height: scrollView.frame.height)
imageView.contentMode = .scaleAspectFit
scrollView.contentSize.width = scrollView.frame.width * CGFloat(i + 1)
scrollView.addSubview(imageView)
//scrollView.delegate = (self as! UIScrollViewDelegate)
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
view.addSubview(scrollView)
imageArray = [#imageLiteral(resourceName: "1"),#imageLiteral(resourceName: "10"),#imageLiteral(resourceName: "9"),#imageLiteral(resourceName: "8"),#imageLiteral(resourceName: "3")]
setupImages(imageArray)
}
}
You will need to add a saveImage function:
func saveImage(image: UIImage) -> Bool {
guard let data = UIImageJPEGRepresentation(image, 1) ?? UIImagePNGRepresentation(image) else {
return false
}
guard let directory = try? FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false) as NSURL else {
return false
}
do {
try data.write(to: directory.appendingPathComponent("fileName.png")!)
return true
} catch {
print(error.localizedDescription)
return false
}
}
And then in saveButtonPressed:
let success = saveImage(image: imageArray[0])
print("Did \(success ? "" : "not ")store image successfully")
You'll need to add some logic to actually select the image.
Related
I'm trying to get PDF from UIView with UILabel text mask.
override func viewDidLoad() {
super.viewDidLoad()
let label = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 200 ))
label.text = "Label Text"
label.font = UIFont.systemFont(ofSize: 25)
label.textAlignment = .center
label.textColor = UIColor.white
let overlayView = UIImageView(frame: CGRect(x: 0, y: 0, width: 200, height: 200 ))
overlayView.image = UIImage(named: "erasemask.png")
label.mask = overlayView
view_process.addSubview(label)
}
func exportAsPdfFromView(){
let pdfPageFrame = CGRect(x: 0, y: 0, width: view_process.bounds.size.width, height: view_process.bounds.size.height)
let pdfData = NSMutableData()
UIGraphicsBeginPDFContextToData(pdfData, pdfPageFrame, nil)
UIGraphicsBeginPDFPageWithInfo(pdfPageFrame, nil)
guard let pdfContext = UIGraphicsGetCurrentContext() else { return "" }
view_process.layer.render(in: pdfContext)
UIGraphicsEndPDFContext()
let path = self.saveViewPdf(data: pdfData)
print(path)
}
func saveViewPdf(data: NSMutableData) -> String {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let docDirectoryPath = paths[0]
let pdfPath = docDirectoryPath.appendingPathComponent("viewPdf.pdf")
if data.write(to: pdfPath, atomically: true) {
return pdfPath.path
} else {
return ""
}
}
but I do not get PDF with mask. I don't want to convert UIView to UImage and then convert UImage to PDF. I want to editable PDF so don't want to convert into UIImage.
Can anyone help me How to convert Masked UILabel to PDF ?
here erasemask.png
You have to draw text yourself in the pdf to make it editable.
I have slightly modified your code, and it works. You can simply copy/paste in a new app view controller to check the result.
Here is a screenshot of the document opened in AffinityDesigner. The mask is correctly applied as a layer mask, and the text is editable.
It needs some tweaking to respect exact layout.
import UIKit
class ViewController: UIViewController {
var labelFrame: CGRect { return CGRect(x: 0, y: 0, width: 200, height: 200 )}
lazy var label: UILabel = {
let label = UILabel(frame: labelFrame)
label.text = "Label Text"
label.font = UIFont.systemFont(ofSize: 25)
label.textAlignment = .center
label.textColor = UIColor.black
return label
}()
var maskImage = UIImage(named: "erasemask.png")
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(label)
let overlayView = UIImageView(frame: labelFrame)
overlayView.image = maskImage
label.mask = overlayView
exportAsPdfFromView()
}
func exportAsPdfFromView() {
let pdfPageFrame = CGRect(x: 0, y: 0, width: view.bounds.size.width, height: view.bounds.size.height)
let pdfData = NSMutableData()
UIGraphicsBeginPDFContextToData(pdfData, pdfPageFrame, nil)
UIGraphicsBeginPDFPageWithInfo(pdfPageFrame, nil)
guard let context = UIGraphicsGetCurrentContext() else { return }
// Clip context
if let overlayImage = maskImage?.cgImage {
context.clip(to: labelFrame, mask: overlayImage)
}
// Draw String
let string: String = label.text ?? ""
let attributes: [NSAttributedString.Key: Any] = [
NSAttributedString.Key.foregroundColor: label.textColor ?? .black,
NSAttributedString.Key.font: label.font ?? UIFont.systemFont(ofSize: 25)
]
let stringRectSize = string.size(withAttributes: attributes)
let x = (labelFrame.width - stringRectSize.width) / 2
let y = (labelFrame.height - stringRectSize.height) / 2
let stringRect = CGRect(origin: CGPoint(x: x, y: y), size: stringRectSize)
string.draw(in: stringRect, withAttributes: attributes)
UIGraphicsEndPDFContext()
saveViewPdf(data: pdfData)
}
func saveViewPdf(data: NSMutableData) {
guard let docDirectoryPath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return }
let pdfPath = docDirectoryPath.appendingPathComponent("viewPdf.pdf")
print(pdfPath)
data.write(to: pdfPath, atomically: true)
}
}
EDITED
As a comparison, I have added the result by using the Apple view.render function, using code from the question ( with a blue background so we can see white text ). It clearly shows that this function does not support editable text and masking.
It exports the document as a stack of flat images and extra - useless - groups.
So I guess the only solution to keep pdf entities types is to compose the document by rendering each object.
If you need to export complex forms, it must not be too hard to make a helper that crawls in the view hierarchy and render each object content.
If you need to also render pdf with interactive buttons, you will probably need to use Annotations( available in PDFKit ). By the way you can also create editable fields with annotations, but I'm not sure it supports masking.
LAST EDIT:
Since you use an external framework to render pdf ( PDFGenerator ), it is different. You can only override the view.layer.render function that is used by the framework and use the context.clip function.
To export ui components as editable, I think they must have no superview. As soon as there is a view hierarchy, a backing bitmap is created, and all render calls are made with this bitmap as parameter, and not the PDFContext that was used to call the first render.
That's how PDFGenerator works, it crawls in the view hierarchy an render views by removing them from superview, render to the context, and move them back in hierarchy.
The big drawback of this is that it leads to bugs when the view is moved back in the hierarchy. Probably because constraints are lost, or some views like UIStackView behave differently. There is numerous opened issues around this on their github.
What I don't really understand yet is why the label below is rendered as editable even in a view hierarchy. I guess it's due to how the render function is done by Apple. Can't go further on this right now..
Custom Field Example:
It may need more work to respect exact field layout, but this is a basis for a view that is rendered as editable text. It gives the exact same result as in the first part of the answer.
It works with any mask view, not only UIImage.
It is rendered as editable even in a hierarchy.
So if you use this label instead of UILabel in the initial code of this question, it works.
// Extension to get mask view as an image
extension UIView {
var cgImage: CGImage? {
UIGraphicsBeginImageContextWithOptions(bounds.size, isOpaque, contentScaleFactor);
guard let context = UIGraphicsGetCurrentContext() else { return nil }
layer.render(in: context)
let image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image?.cgImage
}
}
class PMLayer: CALayer {
// Needed to access text style
weak var label: UILabel?
override init() { super.init() }
required init?(coder: NSCoder) { super.init(coder: coder) }
override init(layer: Any) {
super.init(layer: layer)
if let pm = layer as? PMLayer {
label = pm.label
}
}
override func render(in ctx: CGContext) {
guard let label = label else { return }
// Clip context
if let mask = label.mask?.cgImage {
ctx.clip(to: label.frame, mask: mask)
}
// Draw String
let string: String = label.text ?? ""
let attributes: [NSAttributedString.Key: Any] = [
NSAttributedString.Key.foregroundColor: label.textColor ?? .black,
NSAttributedString.Key.font: label.font ?? UIFont.systemFont(ofSize: 25)
]
let stringRectSize = string.size(withAttributes: attributes)
let x = (label.frame.width - stringRectSize.width) / 2
let y = (label.frame.height - stringRectSize.height) / 2
let stringRect = CGRect(origin: CGPoint(x: x, y: y), size: stringRectSize)
string.draw(in: stringRect, withAttributes: attributes)
}
}
class PMLabel: UILabel {
override class var layerClass: AnyClass { return PMLayer.self }
// Be sure the label is correctly linked to the layer when we access it
override var layer: CALayer {
(super.layer as? PMLayer)?.label = self
return super.layer
}
}
this is my decision
import UIKit
import PDFKit
class ViewController: UIViewController {
#IBOutlet weak var view_process: UIView!
#IBOutlet weak var pdf_view: UIView!
let documentInteractionController = UIDocumentInteractionController()
#IBAction func bClick(_ sender: Any) {
exportAsPdfFromView()
}
override func viewDidLoad() {
super.viewDidLoad()
documentInteractionController.delegate = self
let label = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 200 ))
label.text = "Label Text"
label.font = UIFont.systemFont(ofSize: 25)
label.textAlignment = .center
label.textColor = UIColor.blue
let overlayView = UIImageView(frame: CGRect(x: 0, y: 0, width: 200, height: 200 ))
overlayView.image = UIImage(named: "erasemask.png")
label.mask = overlayView
view_process.addSubview(label)
}
func exportAsPdfFromView(){
let pdfPageFrame = view_process.bounds//.CGRect(x: 0, y: 0, width: view_process.bounds.size.width, height: view_process.bounds.size.height)
let pdfData = NSMutableData()
UIGraphicsBeginPDFContextToData(pdfData, pdfPageFrame, nil)
UIGraphicsBeginPDFPageWithInfo(pdfPageFrame, nil)
let pdfContext = UIGraphicsGetCurrentContext()!
view_process.layer.render(in: pdfContext)
UIGraphicsEndPDFContext()
let path = self.saveViewPdf(data: pdfData)
print(path)
self.share(url: URL(string: "file://\(path)")!)
}
func saveViewPdf(data: NSMutableData) -> String {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let docDirectoryPath = paths[0]
let pdfPath = docDirectoryPath.appendingPathComponent("viewPdf.pdf")
if data.write(to: pdfPath, atomically: true) {
return pdfPath.path
} else {
return ""
}
}
func openPdf(path: String) {
let pdfView = PDFView(frame: self.view.bounds)
pdfView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
pdf_view.addSubview(pdfView)
// Fit content in PDFView.
pdfView.autoScales = true
// Load Sample.pdf file from app bundle.
let fileURL = URL(string: path)
pdfView.document = PDFDocument(url: fileURL!)
}
func share(url: URL) {
documentInteractionController.url = url
// documentInteractionController.uti = url.typeIdentifier ?? "public.data, public.content"
// documentInteractionController.name = url.localizedName ?? url.lastPathComponent
documentInteractionController.presentPreview(animated: true)
}
}
extension ViewController: UIDocumentInteractionControllerDelegate {
func documentInteractionControllerViewControllerForPreview(_ controller: UIDocumentInteractionController) -> UIViewController {
guard let navVC = self.navigationController else {
return self
}
return navVC
}
}
I have a customLoader which I would like to call anytime a user logs in. I want to animate thru all seven photos in gifArray.
import UIKit
class CustomLoader: UIView {
static let instance = CustomLoader()
let gifArray: [UIImage] = [UIImage(named: "beer1")!,UIImage(named: "beer2")!,UIImage(named: "beer3")!,UIImage(named: "beer4")!,UIImage(named: "beer5")!,UIImage(named: "beer6")!,UIImage(named: "beer7")!]
lazy var transparentView:UIView = {
let transparentView = UIView(frame: UIScreen.main.bounds)
transparentView.backgroundColor = UIColor.black.withAlphaComponent(0.7)
transparentView.isUserInteractionEnabled = false
return transparentView
} ()
lazy var gifImage: UIImageView = {
var gifImage = UIImageView(frame: CGRect(x: 0, y: 0, width: 200.00, height: 100))
gifImage.contentMode = .scaleAspectFit
gifImage.center = transparentView.center
gifImage.isUserInteractionEnabled = false
return gifImage
} ()
func animate() {
for image in gifArray {
gifImage.image = image
gifImage.animationRepeatCount = 1
gifImage.startAnimating()
}
}
func showLoader() {
self.addSubview(transparentView)
self.transparentView.addSubview(gifImage)
self.transparentView.bringSubviewToFront(self.gifImage)
animate()
}
func hideLoader() {
self.transparentView.removeFromSuperview()
}
}
I call it when the user logs in
In ViewDidLoad:
CustomLoader.instance.showLoader()
view.addSubview(CustomLoader.instance.transparentView)
view.bringSubviewToFront(CustomLoader.instance.transparentView)
Problem: It unfortunately just shows the last image. How do i fix this?
The for loop here sets the last image
for image in gifArray {
instead you need
gifImage.isUserInteractionEnabled = false
gifImage.animationImages = gifArray
Then
func animate() {
gifImage.startAnimating()
}
I am a beginner to Swift, so I would probably need some explaining. Please bear with me. I am creating an app that needs to load a .gif file, but when I run it on the simulator it loads for one second (or even less) and then becomes blank, but the screen itself stays on the page that had the .gif file on it. I'm not sure why this happens. Can someone explain? Thank you!
Here is the code:
import UIKit
class ViewController: UIViewController {
#IBAction func Burning(sender: AnyObject) {
let imageData = NSData(contentsOfURL: NSBundle.mainBundle().URLForResource("fire", withExtension: "gif")!)
let imageGif = UIImage.gifWithData(imageData!)
let imageView = UIImageView(image: imageGif)
imageView.frame = CGRect(x: 0.0, y:0.0, width:414.0, height: 685.0)
view.addSubview(imageView)
}
#IBAction func Smashing(sender: AnyObject) {
let imageData = NSData(contentsOfURL: NSBundle.mainBundle().URLForResource("water", withExtension: "gif")!)
let imageGif = UIImage.gifWithData(imageData!)
let imageView = UIImageView(image: imageGif)
imageView.frame = CGRect(x: 0.0, y:0.0, width:414.0, height: 685.0)
view.addSubview(imageView)
}
#IBAction func Shredding(sender: AnyObject) {
let imageData = NSData(contentsOfURL: NSBundle.mainBundle().URLForResource("shredder", withExtension: "gif")!)
let imageGif = UIImage.gifWithData(imageData!)
let imageView = UIImageView(image: imageGif)
imageView.frame = CGRect(x: 0.0, y:0.0, width:414.0, height: 685.0)
view.addSubview(imageView)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
I am trying to make an infinite loop image gallery app. I did it by setting up a UIScrollView inside which I inserted UIImageViews.
I am able to load 4 images and swipe between them, but the problem I have is how to implement the infinite scroll, so that after the last image, the first one appears and opposite.
As I am newbie in Swift, I don't know how to handle this problem nor where to start. I will appreciate any suggestion, example or link on how to solve this problem.
Thanks in advance!
Here is the peace of my code:
class FirstViewController: UIViewController {
#IBOutlet weak var scrollView: UIScrollView!
override func viewDidLoad() {
super.viewDidLoad()
self.scrollView.frame = CGRectMake(0, 0, self.view.frame.width, self.view.frame.height)
let scrollViewWidth: CGFloat = self.scrollView.frame.width
let scrollViewHeight: CGFloat = self.scrollView.frame.height
let numPics: Int = 3
let imgOne = UIImageView()
let imgTwo = UIImageView()
let imgThree = UIImageView()
let imgFour = UIImageView()
var arrPics = [imgOne, imgTwo, imgThree, imgFour]
var arrSlide = ["slide1.png", "slide2.png", "slide3.png", "slide4.png"]
for i in 0...numPics {
arrPics[i] = UIImageView(frame: CGRectMake(0,scrollViewHeight * CGFloat(i),scrollViewWidth, scrollViewHeight))
arrPics[i].image = UIImage(named: arrSlide[i])
self.scrollView.addSubview(arrPics[i])
}
self.scrollView.contentSize = CGSizeMake(self.scrollView.frame.width, self.scrollView.frame.height*4)
}
Don't use a scroll view but either a table view or a collection view.
The delegates of both classes want a cell count from you. Then give the delegates an insane number of cells, a number so high that it is totally unlikely that any human being will ever scroll to reach the end. Something like 9999999 cells. This is no problem for such classes because in the background implementation they do not create really this high number of cells but only maximal the number of cells which could be visible at the same time on the screen. The cells in fact are reused. So when cells are falling out at the bottom those cells are going to be reused at the top and vice versa. As a last point is: set the starting point in the middle of such a high number, something like 5555555. I think that is the easiest solution if you are not going to implement a full image recycling algorithm like they did.
#IBOutlet weak var scrollView: UIScrollView!
var scrollViewHeight: CGFloat!
let numPics: Int = 4
override func viewDidLoad()
{
super.viewDidLoad()
scrollView.delegate = self
self.scrollView.frame = CGRectMake(0, 0, self.view.frame.width, self.view.frame.height)
let scrollViewWidth: CGFloat = self.scrollView.frame.width
scrollViewHeight = self.scrollView.frame.height
let imgOne = UIImageView()
let imgTwo = UIImageView()
let imgThree = UIImageView()
let imgFour = UIImageView()
let imgFive = UIImageView()
var arrPics = [imgOne, imgTwo, imgThree, imgFour,imgFive]
var arrSlide = ["slide1.jpeg", "slide1.jpeg", "slide1.jpeg", "slide1.jpeg","slide1.jpeg"]
for i in 0...numPics {
arrPics[i] = UIImageView(frame: CGRectMake(0,scrollViewHeight * CGFloat(i),scrollViewWidth, scrollViewHeight))
arrPics[i].image = UIImage(named: arrSlide[i])
self.scrollView.addSubview(arrPics[i])
}
self.scrollView.contentSize = CGSizeMake(self.scrollView.frame.width, self.scrollView.frame.height * CGFloat(numPics+1))
}
func scrollViewDidScroll(scrollView: UIScrollView)
{
scrollViewHeight = self.scrollView.frame.height
self.scrollView.contentSize = CGSizeMake(self.scrollView.frame.width, self.scrollView.frame.height * scrollViewHeight )
}
Using Timer you can use infinite scrolling like below
func showview() {
if(videosimageslider.isEmpty) {
// print("Empty Array")
} else {
// print("Not Empty ")
// print(videosimageslider.count)
for var index=0; index<videosimageslider.count; index++ {
if let url = NSURL(string: videosimageslider[index]) {
if let data = NSData(contentsOfURL: url){
if let imageUrl = UIImage(data: data) {
let myimageview:UIImageView = UIImageView()
// myimageview.image = imageUrl
let block: SDWebImageCompletionBlock! = {(image: UIImage!, error: NSError!, cacheType: SDImageCacheType, imageUrl: NSURL!) -> Void in
//println(self)
}
// let url = NSURL(string: "http://yikaobang-test.u.qiniudn.com/FnZTPYbldNXZi7cQ5EJHmKkRDTkj")
myimageview.sd_setImageWithURL(url, completed: block)
myimageview.frame.size.width = imagewidth
myimageview.frame.size.height = imageheight
myimageview.contentMode = UIViewContentMode.ScaleToFill
myimageview.frame.origin.x = xscrollpos
myimageview.frame.origin.y = 5
scrollview!.addSubview(myimageview)
xscrollpos += imagewidth
scrollviewcontentSize += imagewidth
scrollview.contentSize = CGSize(width: scrollviewcontentSize, height: imageheight)
}
}
}
}
scrollingTimer = NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: "newStartScrolling", userInfo: nil, repeats: true)
scrollingTimer.fire()
}
}
// call the timer function //
func newStartScrolling() {
var currentOffset = scrollview.contentOffset
currentOffset = CGPointMake(currentOffset.x+3, currentOffset.y )
if(currentOffset.x < scrollview.contentSize.width - 500) {
scrollview.setContentOffset(currentOffset, animated: false)
currentOffset = CGPointMake(0, currentOffset.y )
//scrollview.contentSize = CGSize(width: 0, height: 0);
} else {
scrollingTimer.invalidate()
showview()
}
}
This is what will solve your problem, just adjust the controller to go in vertical slide view and load the resources at your will.
Link
I want to build a facebook-like image gallery but don't know where to start from.
Here's what i think i should do:
CollectionView that shows thumbnails based on an array
On row-click, i modally open a pageViewController based on the same array of images
On Swipe left-right, i go to the next or previous image
On Swipe up-down, i close this view and go back to my collectionview
Is this logic correct/the best practice?
Maybe it's been already done by someone.
You can use banana library for showing images in slider view in Swift
get banana from https://github.com/gauravkatoch007/banana
import banana
#IBOutlet weak var imageScrollView: UIScrollView!
// Here imageArray can be a string array of Image URLs
var imageArray = [String]()
//or imageArray can be a array of UIImages
var imageArray = [UIImage]()
var imageScroll = banana( imageScrollView :self.imageScrollView )
//Load to load images in memory and display them in User Interface
imageScroll!.load(imageArray)
//Call startScroll for autoScrolling. Default scrolling timer is 8 seconds
imageScroll!.startScroll()
//Call this function to stop autoScrolling on touch or swipe.
imageScroll!.assignTouchGesture()
Update I resolved in this way:
Gallery is a collection view
On cell selected, i modally segue to another view, which contains a scrollview in which i put 5 images one (right) after the other, and handle paginating.
My image will always be the third in the middle, after every scroll, i choose the 5 images of my entire array which centers the index, or the 5 which contain this.
here's my class PhotoViewController: UIViewController, UIScrollViewDelegate {
var screenSize: CGRect = UIScreen.mainScreen().bounds
#IBOutlet weak var scrollView: UIScrollView!
#IBOutlet weak var blackView: UIView!
#IBOutlet weak var doneButton: UIButton!
#IBOutlet weak var photoActions: UIImageView!
var img1:UIImageView = UIImageView(image: UIImage())
var img2:UIImageView = UIImageView(image: UIImage())
var img3:UIImageView = UIImageView(image: UIImage())
var img4:UIImageView = UIImageView(image: UIImage())
var img5:UIImageView = UIImageView(image: UIImage())
var w1: UIImage!
var w2: UIImage!
var w3: UIImage!
var w4: UIImage!
var w5: UIImage!
var pageIndex: Int!
var currentPage: Int!
var oldPage: Int!
var endFrame: CGRect!
var arrayIndex: Int!
// placeholder for if the image frame is scrolled
var scrolledPhotoFrame: CGRect!
override func viewDidLoad() {
super.viewDidLoad()
RightSize()
LoadData()
}
func LoadData(){
// data passed from feedViewController gets stored here
img1.image = w1
img2.image = w2
img3.image = w3
img4.image = w4
img5.image = w5
// set the right endFrame based on the selectedImage
switch pageIndex {
case 0:
img1.frame = endFrame
img1.frame.origin.x = 0
case 1:
img2.frame = endFrame
img2.frame.origin.x = screenSize.width
case 2:
img3.frame = endFrame
img3.frame.origin.x = (screenSize.width * 2)
case 3:
img4.frame = endFrame
img4.frame.origin.x = (screenSize.width * 3)
case 4:
img5.frame = endFrame
img5.frame.origin.x = (screenSize.width * 4)
default:
break
}
currentPage = pageIndex
oldPage = pageIndex
scrollView.contentSize = CGSize(width: screenSize.width*5, height: screenSize.height)
scrollView.contentOffset.x = CGFloat(pageIndex * Int(screenSize.width))
println(scrollView.contentOffset.x)
// default value of scrolledPhotoFrame is unscrolled position of photoImageView
scrolledPhotoFrame = endFrame
// required for registering scroll events
scrollView.delegate = self
// RightSize()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func doneDidPress(sender: AnyObject) {
dismissViewControllerAnimated(true, completion: nil)
}
// called while scrolling
func scrollViewDidScroll(scrollView: UIScrollView) {
currentPage = Int(scrollView.contentOffset.x / screenSize.width)
if (currentPage != oldPage){
//Ho cambiato pagina
if (currentPage>oldPage){
//Sono andato di 1 foto avanti
println("Avanti")
arrayIndex = arrayIndex+1
CambioPagina()
}else{
//Sono andato di 1 foto indietro
arrayIndex = arrayIndex-1
println("indietro")
}
oldPage=currentPage
}
var alpha = CGFloat(1 - abs(scrollView.contentOffset.y) / 100)
var alpha2 = CGFloat(1 - abs(scrollView.contentOffset.y) / 20)
blackView.alpha = alpha
doneButton.alpha = alpha2
photoActions.alpha = alpha2
}
// This method is called right as the user lifts their finger
func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
var offsetY = scrollView.contentOffset.y
var alpha = CGFloat(1 - abs(scrollView.contentOffset.y) / 240)
if (abs(offsetY) > 100) {
scrolledPhotoFrame.origin.y = scrolledPhotoFrame.origin.y - offsetY
blackView.hidden = true
scrollView.hidden = true // could be wrong
doneButton.hidden = true
dismissViewControllerAnimated(true, completion: nil)
}
}
// selecting the view to zoom
func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
switch currentPage {
case 0:
return img1
case 1:
return img2
case 2:
return img3
case 3:
return img4
case 4:
return img5
default:
return nil
}
}
func scrollViewWillBeginZooming(scrollView: UIScrollView, withView view: UIView!) {
img2.hidden = true
img3.hidden = true
img4.hidden = true
img5.hidden = true
}
func scrollViewDidEndZooming(scrollView: UIScrollView, withView view: UIView!, atScale scale: CGFloat) {
}
//Controllo per cambio pagina..! chissa!
func CambioPagina(){
switch arrayIndex{
case 0:
w1 = UIImage(named: arrayFoto[arrayIndex])
w2 = UIImage(named: arrayFoto[arrayIndex+1])
w3 = UIImage(named: arrayFoto[arrayIndex+2])
w4 = UIImage(named: arrayFoto[arrayIndex+3])
w5 = UIImage(named: arrayFoto[arrayIndex+4])
pageIndex = 0
case 1:
w1 = UIImage(named: arrayFoto[arrayIndex-1])
w2 = UIImage(named: arrayFoto[arrayIndex])
w3 = UIImage(named: arrayFoto[arrayIndex+1])
w4 = UIImage(named: arrayFoto[arrayIndex+2])
w5 = UIImage(named: arrayFoto[arrayIndex+3])
pageIndex = 1
case (arrayFoto.count-2):
w1 = UIImage(named: arrayFoto[arrayIndex-3])
w2 = UIImage(named: arrayFoto[arrayIndex-2])
w3 = UIImage(named: arrayFoto[arrayIndex-1])
w4 = UIImage(named: arrayFoto[arrayIndex])
w5 = UIImage(named: arrayFoto[arrayIndex+1])
pageIndex = 3
case (arrayFoto.count-1):
w1 = UIImage(named: arrayFoto[arrayIndex-4])
w2 = UIImage(named: arrayFoto[arrayIndex-3])
w3 = UIImage(named: arrayFoto[arrayIndex-2])
w4 = UIImage(named: arrayFoto[arrayIndex-1])
w5 = UIImage(named: arrayFoto[arrayIndex])
pageIndex = 4
default:
w1 = UIImage(named: arrayFoto[arrayIndex-2])
w2 = UIImage(named: arrayFoto[arrayIndex-1])
w3 = UIImage(named: arrayFoto[arrayIndex])
w4 = UIImage(named: arrayFoto[arrayIndex+1])
w5 = UIImage(named: arrayFoto[arrayIndex+2])
pageIndex = 2
}
LoadData()
}
func RightSize(){
img1.frame = CGRect(x: 0, y: 0, width: screenSize.width, height: screenSize.height)
scrollView.addSubview(img1)
img2.frame = CGRect(x: screenSize.width, y: 0, width: screenSize.width, height: screenSize.height)
scrollView.addSubview(img2)
img3.frame = CGRect(x: (screenSize.width*2), y: 0, width: screenSize.width, height: screenSize.height)
scrollView.addSubview(img3)
img4.frame = CGRect(x: (screenSize.width*3), y: 0, width: screenSize.width, height: screenSize.height)
scrollView.addSubview(img4)
img5.frame = CGRect(x: (screenSize.width*4), y: 0, width: screenSize.width, height: screenSize.height)
scrollView.addSubview(img5)
img1.contentMode = .ScaleAspectFit
img2.contentMode = .ScaleAspectFit
img3.contentMode = .ScaleAspectFit
img4.contentMode = .ScaleAspectFit
img5.contentMode = .ScaleAspectFit
}
Any better approach will be great, for example, i cannot handle image zoom