Подтвердить что ты не робот

Рисование текста над Core Graphics в Swift 3

Фон: Я рисую UIImageView с помощью Core Graphics. Я хотел бы в конечном итоге нарисовать текстовую строку над основным графическим рисунком.

Этот метод (hackingwithswift.com), который я использовал, чтобы нарисовать текст для изображения, установить для него изображение ImageView и затем нарисовать с основной графикой. Но я хочу, чтобы текст накладывал основной графический чертеж.

Теперь я перешел на этот qaru.site/info/1264815/..., но он все еще не позволяет мне писать поверх моего рисунка.

class MapViewController: UIViewController {

    @IBOutlet var imageView: UIImageView!

    func drawScale() {
        // establish 6 points to draw a little bar with
        let length = CGFloat(80.0)
        let bottom = imageView.bounds.size.height - 15.0
        let left = CGFloat(20.0)
        let top = bottom - 20.0
        let middle = top + 10.0
        let right = left + length
        let topLeft = CGPoint(x: left, y: top)
        let topRight = CGPoint(x: right, y: top)
        let bottomRight = CGPoint(x: right, y: bottom)
        let bottomLeft = CGPoint(x: left, y: bottom)
        let middleLeft = CGPoint(x: left, y: middle)
        let middleRight = CGPoint(x: right, y: middle)

        // draw the bar
        drawLineFrom(fromPoint: topLeft, toPoint: bottomLeft, color: UIColor.red.cgColor, width: 1.0, alias: false)
        drawLineFrom(fromPoint: topRight, toPoint: bottomRight, color: UIColor.red.cgColor, width: 1.0, alias: false)
        drawLineFrom(fromPoint: middleLeft, toPoint: middleRight, color: UIColor.red.cgColor, width: 1.0, alias: false)

        // draw a text string
        UIGraphicsBeginImageContext(self.imageView.frame.size)

        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.alignment = .center

        let attrs = [
            NSFontAttributeName: UIFont.systemFont(ofSize: 12),
            NSParagraphStyleAttributeName: paragraphStyle,
            NSForegroundColorAttributeName: UIColor.red]

        let scaleString = "45 feet"
        scaleString.draw(at: CGPoint(x: 0, y: 50), withAttributes: attrs)

        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
    }

    /* Stroke a line between two CGPoints. Color, width, anti-alias options. */
    func drawLineFrom(fromPoint: CGPoint, toPoint: CGPoint, color: CGColor, width: CGFloat, alias: Bool) {
        // 1
        UIGraphicsBeginImageContext(self.imageView.frame.size)
        let context = UIGraphicsGetCurrentContext()!
        context.setShouldAntialias(alias)
        self.imageView.image?.draw(in: CGRect(x: 0, y: 0, width: self.imageView.frame.size.width, height: self.imageView.frame.size.height))

        // 2
        context.move(to: fromPoint)
        context.addLine(to: toPoint)

        // 3
        context.setLineWidth(width)
        context.setStrokeColor(color)

        // 4
        context.strokePath()

        // 5
        self.imageView.image = UIGraphicsGetImageFromCurrentImageContext()
        self.imageView.alpha = 1.0
        UIGraphicsEndImageContext()
    }
}

Не работает. Рисование текстовой строки полностью стирает панель. Если переместить код рисования штрих-кода под кодом строкового рисунка, то оба они видны, но, конечно, строка затем над строкой.

4b9b3361

Ответ 1

Используя Swift 4:

let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .center

let attributes = [
    NSAttributedStringKey.paragraphStyle: paragraphStyle,
    NSAttributedStringKey.font: UIFont.systemFont(ofSize: 12.0),
    NSAttributedStringKey.foregroundColor: UIColor.blue
]

let myText = "HELLO"
let attributedString = NSAttributedString(string: myText, attributes: attributes)

let stringRect = CGRect(x: W/2 - 50, y: border, width: 100, height: H)
attributedString.draw(in: stringRect)

Для Swift 4.2 измените вышеуказанные attributes на:

let attributes: [NSAttributedString.Key : Any] = [
    .paragraphStyle: paragraphStyle,
    .font: UIFont.systemFont(ofSize: 12.0),
    .foregroundColor: UIColor.blue
]

Ответ 2

Swift 3.0: рисование текста

   func drawMyText(myText:String,textColor:UIColor, FontName:String, FontSize:CGFloat, inRect:CGRect){

     let textFont = UIFont(name: FontName, size: FontSize)!
    let textFontAttributes = [
        NSFontAttributeName: textFont,
        NSForegroundColorAttributeName: textColor,
        ] as [String : Any]

    myText.draw(in: inRect, withAttributes: textFontAttributes)
}

вызов этой функции, например, ниже

let _rect = CGRect(x: 40, y: 100, width: 40, height: 40)

 drawMyText(myText: "Hello", textColor: UIColor.black, FontName: "Helvetica Bold", FontSize: 11 , inRect:_rect)