Picture is stretched when I turn a page on Pageviewcontroller

Asked

Viewed 78 times

0

Hello I’m new in Swift and I don’t understand why the image stretches when I turn a page using PageViewController as I will show in the image below: This picture is normal, it’s when I haven’t turned the page. inserir a descrição da imagem aqui

But now there’s the image of when I turn a page forward and go back to the homepage after : inserir a descrição da imagem aqui

Now I will post my code for analysis :

import UIKit
import CoreData

class ViewControllerRevistaImagem: UIViewController , UIPageViewControllerDataSource , UIPageViewControllerDelegate {
    var arrPageTitle: NSArray = NSArray()
    var arrPagePhoto: NSMutableArray = NSMutableArray()
    var arrPagePhoto1: NSMutableArray = NSMutableArray()
    var arrInteiro : NSMutableArray = NSMutableArray()
    var appDelegate : AppDelegate!
    var managedContext : NSManagedObjectContext!
    var viewDidload : Int = Int()
    var pageViewController: UIPageViewController!
    lazy var modelController = ModelController()
    var dataPunicao : NSDate!
    var wiewwilappear : Int = 0
    var x = 0

    override func viewDidLoad() {
        super.viewDidLoad()

        self.navigationController?.hidesBarsOnTap = true

        self.pageViewController = UIPageViewController(transitionStyle: .pageCurl, navigationOrientation: .horizontal, options: nil)
        self.pageViewController!.delegate = self
        self.pageViewController.view.clipsToBounds = true
        if arrPagePhoto.count != 0
        {
            arrPagePhoto.removeAllObjects()
        }

        appDelegate = UIApplication.shared.delegate as! AppDelegate
        managedContext = appDelegate.managedObjectContext

        do
        {
            var user1 : NSManagedObject!
            var user2 : NSManagedObject!
            var titulo2 : String = String()
            var titulo3 : String = String()
            let myFetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Noticias")
            myFetchRequest.returnsObjectsAsFaults = false

            let sortDescriptor = NSSortDescriptor(key: "voto", ascending: false)
            let sortDescriptors = [sortDescriptor]
            myFetchRequest.sortDescriptors = sortDescriptors

            var myFetchResults : [NSManagedObject] = try managedContext.fetch(myFetchRequest) as! [NSManagedObject]
            if(!myFetchResults.isEmpty)
            {

                var i = 0

                if myFetchResults.count >= 2 && myFetchResults[1].value(forKey: "titulo") != nil
                {
                    user1 = myFetchResults[1]
                    titulo2 = (user1.value(forKey: "titulo") as? String)!
                }
                if myFetchResults.count >= 3 && myFetchResults[2].value(forKey: "titulo") != nil
                {
                    user2 = myFetchResults[2]
                    titulo3 = (user2.value(forKey: "titulo") as? String)!
                }
                while(i < myFetchResults.count)
                {
                    let user : NSManagedObject = myFetchResults[i]
                    if user.value(forKey: "foto") != nil
                    {
                        if i == 0
                        {
                            let primeiraPagina = UIImage(named: "imagens/2.jpg")
                            let primeiraPagina2 = UIImageJPEGRepresentation(primeiraPagina!, 0)
                            arrPagePhoto.add(primeiraPagina2)
                            arrInteiro.add(i)

                            var imagem2 : UIImage = UIImage()
                            var imagem2Capa1 : UIImage = UIImage()
                            var imagem2Capa2 : UIImage = UIImage()
                            var imagem2Fundo1 : UIImage = UIImage()
                            var imagem2Fundo2 : UIImage = UIImage()
                            var imagem3 : Data!
                            var imagem3Capa1 : Data!
                            var imagem3Capa2 : Data!
                            var imagem3Fundo1 : Data!
                            var imagem3Fundo2 : Data!

                            if user.value(forKey: "imagem") != nil && user.value(forKey: "titulo") != nil
                            {
                                let imagem = user.value(forKey: "imagem") as? Data
                                let titulo = user.value(forKey: "titulo") as? String

                                imagem2 = textToImage( titulo! as NSString , inImage : UIImage(data: imagem!)! , inImageFundo : UIImage(named: "imagens/fundo.jpg")! ,atPoint:CGPoint(x: 0 , y: 0) , tipoImagem : 1)
                                imagem3 = UIImageJPEGRepresentation(imagem2, 0)

                                arrPagePhoto.add(imagem3)
                                arrInteiro.add(i)
                            }

                            if user1 != nil && user1.value(forKey: "foto") != nil
                            {
                                let imagemCapa1 = user1.value(forKey: "imagem") as? Data
                                arrPagePhoto1[0] = (imagemCapa1)

                                //---------------------------------------------------------------------------------
                                imagem2Fundo1 = textToImage( titulo2 as NSString , inImage : UIImage(data: imagemCapa1!)! , inImageFundo :UIImage(named: "imagens/fundo.jpg")! , atPoint:CGPoint(x: 0, y: 5
                                ) , tipoImagem: 3)
                                imagem3Fundo1 = UIImageJPEGRepresentation(imagem2Fundo1, 0)
                                arrPagePhoto1[1] = (imagem3Fundo1)
                            }

                            if user2 != nil  && user2.value(forKey: "foto") != nil
                            {
                                let imagemCapa2 = user2.value(forKey: "imagem") as? Data

                                arrPagePhoto1[2] = (imagemCapa2)

                                //---------------------------------------------------------------------------------
                                imagem2Fundo2 = textToImage( titulo3 as NSString , inImage : UIImage(data: imagemCapa2!)! , inImageFundo :UIImage(named: "imagens/fundo.jpg")! , atPoint:CGPoint(x: 0, y: 20) , tipoImagem: 5)
                                imagem3Fundo2 = UIImageJPEGRepresentation(imagem2Fundo2, 0)
                                arrPagePhoto1[3] = (imagem3Fundo2)

                            }

                        }
                        arrPagePhoto.add((user.value(forKey: "foto") as? Data)!)
                        arrInteiro.add(i)

                    }
                    i += 1
                }
            }
        }
        catch
        {
            print("Erro na leitura")
        }
        if arrPagePhoto.count > 0
        {
            self.pageViewController!.setViewControllers([getViewControllerAtIndex(0)] as [UIViewController], direction: UIPageViewControllerNavigationDirection.forward, animated: false, completion: nil)
            let startingViewController: PageContentViewController = self.viewControllerAtIndex(0, storyboard: self.storyboard!)!
            let viewControllers = [startingViewController]
            self.pageViewController!.setViewControllers(viewControllers, direction: .forward, animated: false, completion: {done in })

            self.pageViewController!.dataSource = self

            self.addChildViewController(self.pageViewController)
            self.view.addSubview(self.pageViewController.view)

            pageViewController.view.translatesAutoresizingMaskIntoConstraints = false
            let topConstraint = NSLayoutConstraint(item: pageViewController.view , attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: topLayoutGuide, attribute: NSLayoutAttribute.bottom, multiplier: 1.0, constant: 0)
            let bottomConstaint = NSLayoutConstraint(item: pageViewController.view, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: bottomLayoutGuide, attribute: NSLayoutAttribute.top, multiplier: 1.0, constant: 0)
            let leadingConstraint = NSLayoutConstraint(item: pageViewController.view, attribute: NSLayoutAttribute.leading, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.leading, multiplier: 3.0, constant: 0)
            let trailingConstraint = NSLayoutConstraint(item: pageViewController.view, attribute: NSLayoutAttribute.trailing, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.trailing, multiplier: 1.0, constant: 0)
            view.addConstraints([topConstraint, bottomConstaint , leadingConstraint , trailingConstraint])

        }
        var pageViewRect = self.view.bounds
        if UIDevice.current.userInterfaceIdiom == .pad {
            pageViewRect = pageViewRect.insetBy(dx: 40.0, dy: 40.0)
        }
        self.pageViewController!.view.frame = CGRect(x: 0, y: 0, width: self.view.frame.width , height: self.view.frame.height)
        self.pageViewController!.didMove(toParentViewController: self)
        self.view.gestureRecognizers = self.pageViewController!.gestureRecognizers

    }

    override func viewDidAppear(_ animated: Bool) {
        print("2")
        let filepath : String = self.getFilePath()
        if(FileManager.default.fileExists(atPath: filepath))
        {
            let array : NSArray = NSArray(contentsOfFile: filepath)!
            dataPunicao = array.object(at: 3) as! NSDate

            if dataPunicao.compare(NSDate() as Date) == .orderedDescending
            {
                let storyboard = UIStoryboard(name: "Main", bundle: nil)
                let resultadoController: MensagemBloqueio = storyboard.instantiateViewController(withIdentifier: "MensagemBloqueio") as! MensagemBloqueio

                present(resultadoController, animated: true, completion: nil)
            }
        }
    }

    func textToImage(_ drawText: NSString,inImage: UIImage, inImageFundo : UIImage , atPoint:CGPoint , tipoImagem : Int)->UIImage{

        var tamanhoIdealMin : CGFloat = CGFloat()
        var tamanhoIdealAlt : CGFloat = CGFloat()
        var tamanhoIdealLarg : CGFloat = CGFloat()

        tamanhoIdealMin = 100
        tamanhoIdealAlt = 500
        tamanhoIdealLarg = 3000

        let textColor: UIColor = UIColor.black

        let widthImagem = inImage.size.width
        let heightImagem = inImage.size.height
        var tamanhoLegenda : CGFloat = CGFloat()

        if tipoImagem == 1
        {
            if heightImagem > widthImagem
            {
                let quantasVezes : CGFloat = heightImagem - 100
                tamanhoLegenda =  7 + quantasVezes * 0.05
            }
            else if heightImagem < widthImagem || heightImagem == widthImagem
            {
                let quantasVezes : CGFloat = widthImagem - 100
                tamanhoLegenda =  7 + quantasVezes * 0.07
            }
        }
        else
        {
            tamanhoLegenda = 32
        }
        let textFont: UIFont = UIFont(name: "Helvetica Bold", size: tamanhoLegenda)!
        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.alignment = .center

        let scale = UIScreen.main.scale
        print("scale : \(scale)")
        print("inimage.size : \(inImage.size)")
        if tipoImagem == 3 || tipoImagem == 5
        {
            UIGraphicsBeginImageContextWithOptions(inImageFundo.size, false , scale)
        }
        else
        {
            UIGraphicsBeginImageContextWithOptions(inImage.size , false , scale)
        }

        let textFontAttributes = [
            NSFontAttributeName: textFont,
            NSForegroundColorAttributeName: textColor,
            NSParagraphStyleAttributeName: paragraphStyle
        ]

        if tipoImagem == 1
        {
            print("entrou tipo imagem 1")
            if inImage.size.width > inImage.size.height && inImage.size.width >= tamanhoIdealMin && inImage.size.height >= tamanhoIdealMin
            {
                print("entrou tipo imagem 1 if ")
                let width = inImage.size.width
                var height = inImage.size.height

                print("largura : \(width) e altura : \(height)")
                let porcentagemAltura = (height / width) * 100
                //0,75
                let percentFormatter            = NumberFormatter()
                percentFormatter.numberStyle    = NumberFormatter.Style.percent
                percentFormatter.multiplier     = 1
                percentFormatter.minimumFractionDigits = 1
                percentFormatter.maximumFractionDigits = 1

                let porcentagem = percentFormatter.string(from: NSNumber(value: Int(porcentagemAltura)))
                let porcentagemNumero = CGFloat(percentFormatter.number(from: porcentagem!)!)

                height = (porcentagemNumero/100) * tamanhoIdealLarg
                print("height : \(height)")
                print("widhth : \(width)")

                inImage.draw(in: CGRect(x: 0, y: 0, width: inImage.size.width  , height: inImage.size.height))
                let alturaTitulo : CGFloat = inImage.size.height/3 * 2
                let rect: CGRect = CGRect(x: atPoint.x, y: alturaTitulo , width: inImage.size.width, height: inImage.size.height)
                drawText.draw(in: rect, withAttributes: textFontAttributes)

            }
            else if inImage.size.width < inImage.size.height && inImage.size.height >= tamanhoIdealMin && inImage.size.width >= tamanhoIdealMin
            {
                let width = inImage.size.width
                var height = inImage.size.height
                let porcentagemAltura = (height / width) * 100

                let percentFormatter            = NumberFormatter()
                percentFormatter.numberStyle    = NumberFormatter.Style.percent
                percentFormatter.multiplier     = 1
                percentFormatter.minimumFractionDigits = 1
                percentFormatter.maximumFractionDigits = 1

                let porcentagem = percentFormatter.string(from: NSNumber(value: Int(porcentagemAltura)))
                let porcentagemNumero = CGFloat(percentFormatter.number(from: porcentagem!)!)

                height = (porcentagemNumero/100) * tamanhoIdealLarg

                inImage.draw(in: CGRect(x: 0, y: 0 , width: tamanhoIdealLarg , height: height))

                inImage.draw(in: CGRect(x: (inImage.size.width/2) - (tamanhoIdealLarg/2), y: ((tamanhoIdealLarg + 170)/2) - (height/2) , width: tamanhoIdealLarg , height: height))
                let alturaTitulo : CGFloat = inImage.size.height/3 * 2.4
                let rect: CGRect = CGRect(x: atPoint.x, y: alturaTitulo , width: inImage.size.width, height: inImage.size.height)
                drawText.draw(in: rect, withAttributes: textFontAttributes)

            }
        }
        else if tipoImagem == 3
        {
            inImageFundo.draw(in: CGRect(x: 0, y: 0, width: 250 , height: 250))
            let rect: CGRect = CGRect(x: atPoint.x, y: atPoint.y , width: inImageFundo.size.width , height: inImageFundo.size.width)
            drawText.draw(in: rect, withAttributes: textFontAttributes)
        }
        else if tipoImagem == 4
        {
            inImage.draw(in: CGRect(x: 0, y: 0, width: inImage.size.width, height: inImage.size.height))
        }
        else if tipoImagem == 5
        {
            inImageFundo.draw(in: CGRect(x: 0, y: 0, width:  250, height: 250))
            let rect: CGRect = CGRect(x: atPoint.x, y: atPoint.y , width:inImageFundo.size.width , height: inImageFundo.size.height)
            drawText.draw(in: rect, withAttributes: textFontAttributes)
        }

        let newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!

        UIGraphicsEndImageContext()

        return newImage
    }


    func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
        print("print3")
        let pageContent: PageContentViewController = viewController as! PageContentViewController
        var index = pageContent.pageIndex
        if ((index == 0) || (index == NSNotFound)) {
            return nil
        }
        index -= 1;

        return getViewControllerAtIndex(index)
    }

    func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
        print("print4")
        let pageContent: PageContentViewController = viewController as! PageContentViewController
        var index = pageContent.pageIndex
        if (index == NSNotFound) { return nil; }
        index += 1;
        if (index == arrPagePhoto.count) { return nil; }

        return getViewControllerAtIndex(index)
    }

    func pageViewController(_ pageViewController: UIPageViewController, spineLocationFor orientation: UIInterfaceOrientation) -> UIPageViewControllerSpineLocation {


        if (orientation == .portrait) || (orientation == .portraitUpsideDown) || (UIDevice.current.userInterfaceIdiom == .phone) {
            // In portrait orientation or on iPhone: Set the spine position to "min" and the page view controller's view controllers array to contain just one view controller. Setting the spine position to 'UIPageViewControllerSpineLocationMid' in landscape orientation sets the doubleSided property to true, so set it to false here.
            /*
             let currentViewController = self.pageViewController!.viewControllers![0]
             let viewControllers = [currentViewController]
             self.pageViewController!.setViewControllers(viewControllers, direction: .forward, animated: true, completion: {done in })
             */
            //print("portrait")
            //self.pageViewController!.isDoubleSided = false
            //return .min
        }

        let currentViewController : PageContentViewController = self.pageViewController!.viewControllers![0] as! PageContentViewController
        var viewControllers: [UIViewController]

        let indexOfCurrentViewController = self.indexOfViewController(currentViewController)
        if (indexOfCurrentViewController == 0) || (indexOfCurrentViewController % 2 == 0) {
            let nextViewController = self.pageViewController(self.pageViewController!, viewControllerAfter: currentViewController)
            viewControllers = [currentViewController, nextViewController!]

        } else {
            let previousViewController = self.pageViewController(self.pageViewController!, viewControllerBefore: currentViewController)
            viewControllers = [previousViewController!, currentViewController]
        }
        self.pageViewController!.setViewControllers(viewControllers, direction: .forward, animated: true, completion: {done in })
        return .mid
    }

    func getViewControllerAtIndex(_ index: NSInteger) -> PageContentViewController
    {
        let pageContentViewController = self.storyboard?.instantiateViewController(withIdentifier: "PageContentViewController") as! PageContentViewController
        pageContentViewController.strPhotoName = UIImage(data:arrPagePhoto[index] as! Data)!

        if index == 1
        {
            if arrPagePhoto1.count >= 1
            {
                pageContentViewController.strPhotoName1 = UIImage(data:arrPagePhoto1[0] as! Data)!
            }
            if arrPagePhoto1.count >= 2
            {
                pageContentViewController.strPhotoName2 = UIImage(data:arrPagePhoto1[1] as! Data)!
            }
            if arrPagePhoto1.count >= 3
            {
                pageContentViewController.strPhotoName3 = UIImage(data:arrPagePhoto1[2] as! Data)!
            }
            if arrPagePhoto1.count >= 4
            {
                pageContentViewController.strPhotoName4 = UIImage(data:arrPagePhoto1[3] as! Data)!
            }
        }
        pageContentViewController.pageIndex = index

        return pageContentViewController
    }

    func indexOfViewController(_ viewController: PageContentViewController) -> Int {
        if let dataObject: AnyObject = viewController.pageIndex as AnyObject? {
            return self.arrInteiro.index(of: dataObject)
        } else {
            return NSNotFound
        }
    }

    func viewControllerAtIndex(_ index: Int, storyboard: UIStoryboard) ->
        PageContentViewController? {
            if (self.arrPagePhoto.count == 0 || (index >= self.arrPagePhoto.count)){
                return nil
            }
            let viewControllerId: NSString = "PageContentViewController"
            let pageContentViewController = storyboard.instantiateViewController(withIdentifier: viewControllerId as String) as! PageContentViewController
            pageContentViewController.strPhotoName = UIImage(data:arrPagePhoto[index] as! Data)!
            if index == 1
            {
                if arrPagePhoto1.count >= 1
                {
                    pageContentViewController.strPhotoName1 = UIImage(data:arrPagePhoto1[0] as! Data)!
                }
                if arrPagePhoto1.count >= 2
                {
                    pageContentViewController.strPhotoName2 = UIImage(data:arrPagePhoto1[1] as! Data)!
                }
                if arrPagePhoto1.count >= 3
                {
                    pageContentViewController.strPhotoName3 = UIImage(data:arrPagePhoto1[2] as! Data)!
                }
                if arrPagePhoto1.count >= 4
                {
                    pageContentViewController.strPhotoName4 = UIImage(data:arrPagePhoto1[3] as! Data)!
                }
            }
            pageContentViewController.pageIndex = index
            return pageContentViewController
    }

    override var supportedInterfaceOrientations: UIInterfaceOrientationMask
    {
        return UIInterfaceOrientationMask.all
    }

    func getFilePath() -> String
    {
        let userDomainPaths : NSArray = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) as NSArray
        let filePath : String = userDomainPaths.object(at: 0) as! String
        return "\(filePath)myFile.plist"
    }
}

and also :

import UIKit
class PageContentViewController: UIViewController {
@IBOutlet weak var lblTitle: UILabel!
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var imageView1: UIImageView!
@IBOutlet weak var imageView2: UIImageView!
@IBOutlet var imageViewFundo1: UIImageView!
@IBOutlet var imageViewFundo2: UIImageView!
@IBOutlet weak var blurView: UIImageView!

var dataObject: AnyObject?
var pageIndex: Int = 0
var strTitle: String!
var strPhotoName: UIImage = UIImage()
var strPhotoName1: UIImage = UIImage()
var strPhotoName2: UIImage = UIImage()
var strPhotoName3: UIImage = UIImage()
var strPhotoName4: UIImage = UIImage()

override func viewDidLoad() {
    super.viewDidLoad()

    imageView.image = strPhotoName
    imageView1.image = strPhotoName1
    imageView2.image = strPhotoName2
    imageViewFundo1.image = strPhotoName3
    imageViewFundo2.image = strPhotoName4
    blurView.image = strPhotoName

    if pageIndex == 1
    {
        imageView.contentMode = .scaleAspectFit
        imageView.clipsToBounds = true
        imageView1.contentMode = .scaleAspectFit
        imageViewFundo1.contentMode = .scaleAspectFit
        self.imageView.backgroundColor = UIColor.clear

        let bluerEfect = UIBlurEffect(style: UIBlurEffectStyle.light)
        let bluerView = UIVisualEffectView(effect: bluerEfect)
        bluerView.frame = blurView.bounds
        bluerView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        bluerView.alpha = 0.9
        blurView.addSubview(bluerView)

        self.imageView.frame = CGRect(x: 0, y: 0, width: 333.5, height: 200)
        self.blurView.frame = CGRect(x: 0, y: 0, width: 333.5, height: 400)
    }
}

And in sotryboard I added 4 constraints in pin as shown in the image below: inserir a descrição da imagem aqui

And that’s all I did, any help I appreciate.

  • Hi, kind of tricky without seeing your storyboard

  • Hello , but what would you like to see in my storyboard? Anything I try to put

  • I looked at your code superficially, it seemed to me that time you create constraints for the autolayout and time you change the width and height of the image in hand. If that is it advise to adopt one or the other, or turn off the autolayout, or do everything through it.

  • I understood.... is that actually this code was more at the base of the control c control v rs but I will analyze that you said thank you!

  • I tried to make changes to turn off the autolayout or use only autolayout but it hasn’t worked yet...

  • The problem is q can be N things, if you want, put the project somewhere so I download q take a look

  • But you want the whole project? Because these two files are the files that are linked with the problem....

Show 2 more comments

2 answers

0

Try to change the Content Mode option to Aspect Fit, as shown below.

Aspect Fit

0


I managed to solve the problem! I hadn’t tagged clip to Bounds in my view yet just in imageview by changing it worked out.Thank you all.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.