我有UIImage
我试图在特定点展示,但是当我打电话时:
image.draw(at: CGPoint.zero)
图片永远不会显示。但是,如果我使用图片创建UIImageView
并将该图像视图添加到视图层次结构中的UIStackViews
之一,则图像会清晰显示。如何在窗口的原点绘制图像?
答案 0 :(得分:4)
这些绘制方法不会绘制到UIWindow
s / UIView
,它们会绘制到当前CGContext
。
查看文档:{{3}}“在当前上下文中的指定点绘制图像。”
例如:
UIGraphicsBeginImageContext(image.size)
image.draw(at: CGPoint.zero)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
如果你想要某种图像视图或任何“漂浮在你的应用程序之上”,你可以使用容器视图控制器。
这是一个操场,显示了一个快速示例,其中红色正方形是一个“浮动”在应用程序上方的图像视图:
https://developer.apple.com/reference/uikit/uiimage/1624132-draw
//: Playground - noun: a place where people can play
import UIKit
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
class ContainerViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
addImageViewOverlay()
}
func addImageViewOverlay() {
let overlayImageView = UIImageView()
overlayImageView.backgroundColor = UIColor.red
overlayImageView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(overlayImageView)
overlayImageView.widthAnchor.constraint(equalToConstant: 50.0).isActive = true
overlayImageView.heightAnchor.constraint(equalToConstant: 50.0).isActive = true
overlayImageView.topAnchor.constraint(equalTo: view.topAnchor, constant: 10.0).isActive = true
overlayImageView.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 10.0).isActive = true
}
func embed(childController: UIViewController) {
// In a real application you'd remove the existing child controller first
addChildViewController(childController)
childController.view.translatesAutoresizingMaskIntoConstraints = false
view.insertSubview(childController.view, at: 0)
childController.didMove(toParentViewController: self)
childController.view.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
childController.view.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
childController.view.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
childController.view.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
}
}
let containerController = ContainerViewController(nibName: nil, bundle: nil)
containerController.view.frame = CGRect(x: 0.0, y: 0.0, width: 320.0, height: 480.0)
let applicationController = UITabBarController(nibName: nil, bundle: nil)
let tabOneController = UIViewController(nibName: nil, bundle: nil)
tabOneController.title = "One"
let tabTwoController = UIViewController(nibName: nil, bundle: nil)
tabTwoController.title = "Two"
applicationController.viewControllers = [tabOneController, tabTwoController]
containerController.embed(childController: applicationController)
PlaygroundPage.current.liveView = containerController.view