Mike Reed | 331ccfd | 2018-10-25 12:36:06 -0400 | [diff] [blame] | 1 | /* |
| 2 | * Copyright 2018 Google Inc. |
| 3 | * |
| 4 | * Use of this source code is governed by a BSD-style license that can be |
| 5 | * found in the LICENSE file. |
| 6 | */ |
| 7 | |
| 8 | #include "SkTextUtils.h" |
| 9 | |
| 10 | void SkTextUtils::DrawText(SkCanvas* canvas, const void* text, size_t size, SkScalar x, SkScalar y, |
Mike Reed | 3a42ec0 | 2018-10-30 12:53:21 -0400 | [diff] [blame^] | 11 | const SkPaint& origPaint, Align align) { |
Mike Reed | 331ccfd | 2018-10-25 12:36:06 -0400 | [diff] [blame] | 12 | int count = origPaint.countText(text, size); |
| 13 | if (!count) { |
| 14 | return; |
| 15 | } |
| 16 | |
| 17 | SkPaint paint(origPaint); |
| 18 | SkAutoSTArray<32, uint16_t> glyphStorage; |
| 19 | const uint16_t* glyphs; |
| 20 | |
| 21 | if (paint.getTextEncoding() != SkPaint::kGlyphID_TextEncoding) { |
| 22 | glyphStorage.reset(count); |
| 23 | paint.textToGlyphs(text, size, glyphStorage.get()); |
| 24 | glyphs = glyphStorage.get(); |
| 25 | paint.setTextEncoding(SkPaint::kGlyphID_TextEncoding); |
| 26 | } else { |
| 27 | glyphs = static_cast<const uint16_t*>(text); |
| 28 | } |
| 29 | |
| 30 | SkAutoSTArray<32, SkScalar> widthStorage(count); |
| 31 | SkScalar* widths = widthStorage.get(); |
| 32 | paint.getTextWidths(glyphs, count * sizeof(uint16_t), widths); |
| 33 | |
Mike Reed | 3a42ec0 | 2018-10-30 12:53:21 -0400 | [diff] [blame^] | 34 | if (align != kLeft_Align) { |
Mike Reed | 331ccfd | 2018-10-25 12:36:06 -0400 | [diff] [blame] | 35 | SkScalar offset = 0; |
| 36 | for (int i = 0; i < count; ++i) { |
| 37 | offset += widths[i]; |
| 38 | } |
Mike Reed | 3a42ec0 | 2018-10-30 12:53:21 -0400 | [diff] [blame^] | 39 | if (align == kCenter_Align) { |
Mike Reed | 331ccfd | 2018-10-25 12:36:06 -0400 | [diff] [blame] | 40 | offset *= 0.5f; |
| 41 | } |
| 42 | x -= offset; |
| 43 | } |
| 44 | |
| 45 | // Turn widths into h-positions |
| 46 | for (int i = 0; i < count; ++i) { |
| 47 | SkScalar w = widths[i]; |
| 48 | widths[i] = x; |
| 49 | x += w; |
| 50 | } |
| 51 | canvas->drawPosTextH(glyphs, count * sizeof(uint16_t), widths, y, paint); |
| 52 | } |
| 53 | |