How can I draw text in Swift's CoreGraphics context in a UIImageView?

Viewed 13

I'm trying to draw a string in a UIImageView in Swift's CoreGraphics for a dynamic geometry software app. I'm using context graphics for graphing points and lines, but when I try to draw a text string (for example, the length of a line segment), I either get no text (such as in these two examples), or everything else I'm drawing is erased except the text string (sorry, I didn't save examples of that). In the latter case, I could draw other stuff on top of the string, but that isn't really helpful either, since I could only draw a single string (trying to draw a second string erased the first).

Here are two attempts, both of which result in no text string drawn:

        UIGraphicsBeginImageContext(canvas.frame.size)
        canvas.draw(CGRect(x: 0, y: 0, width: canvas.frame.width, height: canvas.frame.height))
        let context = UIGraphicsGetCurrentContext()
        let text="\(value)"
        let font=UIFont(name: "Helvetica", size: 12)!
        let text_style=NSMutableParagraphStyle()
        text_style.alignment=NSTextAlignment.center
        let text_color=UIColor.black
        let attributes=[NSAttributedString.Key.font:font, NSAttributedString.Key.paragraphStyle:text_style, NSAttributedString.Key.foregroundColor:text_color]
        let text_x=coordinates.x
        let text_y=coordinates.y
        let text_rect=CGRect(x: text_x, y: text_y, width: 100, height: font.lineHeight)
        text.draw(in: text_rect.integral, withAttributes: attributes)
        UIGraphicsEndImageContext()
    }```

```override func draw(_ canvas: UIImageView, _ isRed: Bool) {
        UIGraphicsBeginImageContext(canvas.frame.size)
        canvas.draw(CGRect(x: 0, y: 0, width: canvas.frame.width, height: canvas.frame.height))
        let renderer = UIGraphicsImageRenderer(size: CGSize(width: 512, height: 512))
        let img = renderer.image { ctx in
            let paragraphStyle = NSMutableParagraphStyle()
            paragraphStyle.alignment = .center
            let attrs = [NSAttributedString.Key.font: UIFont(name: "HelveticaNeue-Thin", size: 12)!, NSAttributedString.Key.paragraphStyle: paragraphStyle]
            let string = "\(value)"
            string.draw(with: CGRect(x: coordinates.x, y: coordinates.y, width: 100, height: 16), options: .usesLineFragmentOrigin, attributes: attrs, context: nil)
        }
    }```

I have also found a page that says something to the effect that it is impossible to draw text in a UIImageView.  However, it is hard to believe that a graphics system as mature as core graphics wouldn't allow drawing text.
0 Answers
Related