我知道这样的问题已经发布在StackOverflow上,但是尽管遵循了指南,但我仍然无法解决我的问题。
我有一个红色矩形想要放置在视图的中心,但它在原点处逐渐变大,如下所示:
在遵循了一些指南之后,我到达了以下代码,但是矩形根本不呈现。
//: 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中显示结果的物理查看窗口没有更改,因此元素不可见。
我希望对此有所帮助和/或指导。
在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)
您必须制作rectangle = imageView.bounds
,并且必须使用下面的代码来计算imageView的帧