blob: cc1b48ee37d3e23a675bbfbc853e49458ec127e3 [file] [log] [blame]
Mike Reed331ccfd2018-10-25 12:36:06 -04001/*
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
10void SkTextUtils::DrawText(SkCanvas* canvas, const void* text, size_t size, SkScalar x, SkScalar y,
Mike Reed3a42ec02018-10-30 12:53:21 -040011 const SkPaint& origPaint, Align align) {
Mike Reed331ccfd2018-10-25 12:36:06 -040012 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 Reed3a42ec02018-10-30 12:53:21 -040034 if (align != kLeft_Align) {
Mike Reed331ccfd2018-10-25 12:36:06 -040035 SkScalar offset = 0;
36 for (int i = 0; i < count; ++i) {
37 offset += widths[i];
38 }
Mike Reed3a42ec02018-10-30 12:53:21 -040039 if (align == kCenter_Align) {
Mike Reed331ccfd2018-10-25 12:36:06 -040040 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