izik461
izik461

Reputation: 1173

Draw UIView in CGContext

I am trying to draw simple UIView in CGContext. I am drawing a string properly, but the UIView is not being drawn.

Method used for drawing the view:

view.draw(view.layer, in: context)

But it does not work. Is there any other way to draw a UIView in CGContext?

import UIKit
import CoreGraphics

let contextSize = CGSize(width: 400, height: 400)

UIGraphicsBeginImageContextWithOptions(contextSize, false, 0.0)

guard let context = UIGraphicsGetCurrentContext() else {
    fatalError("no context")
}

let size = CGSize(width: 30, height: 20)
let point = CGPoint(x: 20, y: 240)
let rect = CGRect(origin: point, size: size)

let text = "TEST"
let paragraphStyle = NSMutableParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle
paragraphStyle.minimumLineHeight = UIFont.systemFont(ofSize: 6).lineHeight
paragraphStyle.lineBreakMode = .byWordWrapping
paragraphStyle.alignment = .center
let attributes: [NSAttributedString.Key : Any] =  [.font: UIFont.systemFont(ofSize: 12),
                                                   .foregroundColor: UIColor.cyan,
                                                   .paragraphStyle: paragraphStyle]
text.draw(with: rect, options: .usesLineFragmentOrigin, attributes: attributes, context: nil)


let view = UIView()
view.backgroundColor = .magenta
view.layer.borderWidth = 2.0
view.layer.borderColor = UIColor.green.cgColor
view.frame = CGRect(origin: point, size: size)

view.draw(view.layer, in: context)

let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()

Upvotes: 1

Views: 3331

Answers (1)

Matic Oblak
Matic Oblak

Reputation: 16794

I believe what you are looking for is

view.drawHierarchy(in: view.bounds, afterScreenUpdates: true)

This will draw to whatever your current context is being set to. And that should already be your context since you do context = UIGraphicsGetCurrentContext(). I tried it with your code and it seems to work. I got an image with rectangle with borders and some text.

Upvotes: 6

Related Questions