blob: 0ac877d0d0a2d3855e98b847bd2ea6185f448cc3 [file] [log] [blame]
cdaltonb2808cd2014-07-25 14:13:57 -07001/*
2 * Copyright 2014 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 "gm.h"
9#include "SkCanvas.h"
10#include "SkGradientShader.h"
11
12/**
13 * This test exercises drawPosTextH and drawPosText with every text align.
14 */
15static const int kWidth = 480;
16static const int kHeight = 600;
17static const SkScalar kTextHeight = 64.0f;
18static const int kMaxStringLength = 12;
19
halcanary2a243382015-09-09 08:16:41 -070020static void drawTestCase(SkCanvas*, const char*, SkScalar, const SkPaint&);
cdaltonb2808cd2014-07-25 14:13:57 -070021
halcanary2a243382015-09-09 08:16:41 -070022DEF_SIMPLE_GM_BG(glyph_pos_align, canvas, kWidth, kHeight, SK_ColorBLACK) {
cdaltonb2808cd2014-07-25 14:13:57 -070023 SkPaint paint;
24 paint.setTextSize(kTextHeight);
25 paint.setFakeBoldText(true);
26 const SkColor colors[] = { SK_ColorRED, SK_ColorGREEN, SK_ColorBLUE };
27 const SkPoint pts[] = {{0, 0}, {kWidth, kHeight}};
reed2ad1aa62016-03-09 09:50:50 -080028 paint.setShader(SkGradientShader::MakeLinear(pts, colors, nullptr, SK_ARRAY_COUNT(colors),
29 SkShader::kMirror_TileMode));
cdaltonb2808cd2014-07-25 14:13:57 -070030 paint.setTextAlign(SkPaint::kRight_Align);
31 drawTestCase(canvas, "Right Align", kTextHeight, paint);
32
33 paint.setTextAlign(SkPaint::kCenter_Align);
34 drawTestCase(canvas, "Center Align", 4 * kTextHeight, paint);
35
36 paint.setTextAlign(SkPaint::kLeft_Align);
37 drawTestCase(canvas, "Left Align", 7 * kTextHeight, paint);
halcanary2a243382015-09-09 08:16:41 -070038}
cdaltonb2808cd2014-07-25 14:13:57 -070039
halcanary2a243382015-09-09 08:16:41 -070040void drawTestCase(SkCanvas* canvas, const char* text, SkScalar y, const SkPaint& paint) {
cdaltonb2808cd2014-07-25 14:13:57 -070041 SkScalar widths[kMaxStringLength];
42 SkScalar posX[kMaxStringLength];
43 SkPoint pos[kMaxStringLength];
bsalomonfbaace02014-12-12 16:41:46 -080044 int length = SkToInt(strlen(text));
cdaltonb2808cd2014-07-25 14:13:57 -070045 SkASSERT(length <= kMaxStringLength);
46
47 paint.getTextWidths(text, length, widths);
48
49 float originX;
50 switch (paint.getTextAlign()) {
51 case SkPaint::kRight_Align: originX = 1; break;
52 case SkPaint::kCenter_Align: originX = 0.5f; break;
53 case SkPaint::kLeft_Align: originX = 0; break;
54 default: SkFAIL("Invalid paint origin"); return;
55 }
56
57 float x = kTextHeight;
58 for (int i = 0; i < length; ++i) {
59 posX[i] = x + originX * widths[i];
60 pos[i].set(posX[i], i ? pos[i - 1].y() + 3 : y + kTextHeight);
61 x += widths[i];
62 }
63
64 canvas->drawPosTextH(text, length, posX, y, paint);
65 canvas->drawPosText(text, length, pos, paint);
cdaltonb2808cd2014-07-25 14:13:57 -070066}