Центрирование представления в другом представлении и настройка размера представления игровой площадки - PullRequest
0 голосов
/ 09 мая 2020

Я знаю, что подобные вопросы были размещены на StackOverflow, но, несмотря на то, что я следовал руководствам, я не смог справиться со своим вопросом.

У меня есть красный прямоугольник, который я хотел бы разместить в центре представления, но он заканчивается в начале координат, например:

I want to move this rectangle into the center

Следуя некоторым руководствам, я пришел к следующему коду, но прямоугольник не отображается вообще.

//: A UIKit based Playground for presenting user interface

import UIKit
import PlaygroundSupport
import CoreGraphics

class MyViewController : UIViewController {

    var currentDrawType = 0


    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white





        // Buton logic follows

        let button = UIButton(type: .system)
        button.frame = CGRect(x:150, y:500, width:80, height:25)
        button.backgroundColor = .white
        button.setTitle("Test Button", for: .normal)
        button.titleLabel?.textColor = .systemBlue
        button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)

        super.view.addSubview(button)

        // Other


        drawRectangle()

    }


    @objc func buttonAction(sender: UIButton!) {
        currentDrawType += 1

        if currentDrawType > 5 {
            currentDrawType = 0
        }

        switch currentDrawType {
        case 0:
            drawRectangle()
        default:
            break
        }

        print(currentDrawType)
    }

    func drawRectangle() {

        var imageView = UIImageView()
        imageView.frame.origin = super.view.bounds.origin
        imageView.frame.size = CGSize(width:200, height:200)
        imageView.center = super.view.convert(super.view.center, from: imageView)

        super.view.addSubview(imageView)


        UIGraphicsBeginImageContextWithOptions(imageView.frame.size, false, 0)
        let context = UIGraphicsGetCurrentContext()

        let rectangle = imageView.frame

        context!.setFillColor(UIColor.red.cgColor)
        context!.setStrokeColor(UIColor.black.cgColor)
        context!.setLineWidth(10)
        context!.addRect(rectangle)
        // Draw it now
        context!.drawPath(using: CGPathDrawingMode.fillStroke)


        let img = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        imageView.image = img

    }

}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyViewController()

Кроме того, я хотел бы отрегулировать размер основного вид, но я не совсем уверен, как это сделать. Когда у меня была немного другая реализация, я изменил размер, но физическое окно просмотра в Xcode, где отображался результат, не изменилось, и, следовательно, элементы не были видны.

enter image description here

Мне нужна помощь и / или руководство по этому поводу.

Ответы [ 2 ]

1 голос
/ 09 мая 2020

Вы должны сделать rectangle = imageView.bounds и рассчитать фрейм imageView, используя приведенный ниже код

import UIKit
import CoreGraphics

class MyViewController : UIViewController {

    var currentDrawType = 0


    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white





        // Buton logic follows

        let button = UIButton(type: .system)
        button.frame = CGRect(x:150, y:500, width:80, height:25)
        button.backgroundColor = .white
        button.setTitle("Test Button", for: .normal)
        button.titleLabel?.textColor = .systemBlue
        button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)

        super.view.addSubview(button)

        // Other


        drawRectangle()

    }


    @objc func buttonAction(sender: UIButton!) {
        currentDrawType += 1

        if currentDrawType > 5 {
            currentDrawType = 0
        }

        switch currentDrawType {
        case 0:
            drawRectangle()
        default:
            break
        }

        print(currentDrawType)
    }

    func drawRectangle() {
        let imageSize = CGSize(width:200, height:200)
        var imageOrigin = self.view.center
        imageOrigin.x -= imageSize.width/2
        imageOrigin.y -= imageSize.height/2
        let imageView = UIImageView(frame: CGRect(origin:imageOrigin , size: imageSize))

        super.view.addSubview(imageView)


        UIGraphicsBeginImageContextWithOptions(imageView.frame.size, false, 0)
        let context = UIGraphicsGetCurrentContext()

        let rectangle = imageView.bounds

        context!.setFillColor(UIColor.red.cgColor)
        context!.setStrokeColor(UIColor.black.cgColor)
        context!.setLineWidth(10)
        context!.addRect(rectangle)
        // Draw it now
        context!.drawPath(using: CGPathDrawingMode.fillStroke)


        let img = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        imageView.image = img

    }

}
1 голос
/ 09 мая 2020

В func drawRectangle() вы устанавливаете исходную точку с исходной точкой супервизора; который по умолчанию равен x: 0, y: 0.

imageView.frame.origin = super.view.bounds.origin // this make you view to top. 

Чтобы исправить это, вам нужно получить центральную точку обзора.

CGPoint.init(x: view.frame.size.width / 2 , y: view.frame.size.height / 2)

Еще я бы посоветовал вам чтобы использовать здесь ограничение.

    let xConstraint = NSLayoutConstraint(item: imageView, attribute: .CenterX, relatedBy: .Equal, toItem: self.view , attribute: .CenterX, multiplier: 1, constant: 0)
let yConstraint = NSLayoutConstraint(item: imageView, attribute: .CenterY, relatedBy: .Equal, toItem: self.view, attribute: .CenterY, multiplier: 1, constant: 0)
imageView.addConstraint(xConstraint)
imageView.addConstraint(yConstraint)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...