1 /* 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 */ 15 static const int kWidth = 480; 16 static const int kHeight = 600; 17 static const SkScalar kTextHeight = 64.0f; 18 static const int kMaxStringLength = 12; 19 20 static void drawTestCase(SkCanvas*, const char*, SkScalar, const SkPaint&); 21 22 DEF_SIMPLE_GM_BG(glyph_pos_align, canvas, kWidth, kHeight, SK_ColorBLACK) { 23 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}}; 28 SkAutoTUnref<SkShader> grad(SkGradientShader::CreateLinear(pts, colors, nullptr, 29 SK_ARRAY_COUNT(colors), 30 SkShader::kMirror_TileMode)); 31 paint.setShader(grad); 32 33 34 paint.setTextAlign(SkPaint::kRight_Align); 35 drawTestCase(canvas, "Right Align", kTextHeight, paint); 36 37 paint.setTextAlign(SkPaint::kCenter_Align); 38 drawTestCase(canvas, "Center Align", 4 * kTextHeight, paint); 39 40 paint.setTextAlign(SkPaint::kLeft_Align); 41 drawTestCase(canvas, "Left Align", 7 * kTextHeight, paint); 42 } 43 44 void drawTestCase(SkCanvas* canvas, const char* text, SkScalar y, const SkPaint& paint) { 45 SkScalar widths[kMaxStringLength]; 46 SkScalar posX[kMaxStringLength]; 47 SkPoint pos[kMaxStringLength]; 48 int length = SkToInt(strlen(text)); 49 SkASSERT(length <= kMaxStringLength); 50 51 paint.getTextWidths(text, length, widths); 52 53 float originX; 54 switch (paint.getTextAlign()) { 55 case SkPaint::kRight_Align: originX = 1; break; 56 case SkPaint::kCenter_Align: originX = 0.5f; break; 57 case SkPaint::kLeft_Align: originX = 0; break; 58 default: SkFAIL("Invalid paint origin"); return; 59 } 60 61 float x = kTextHeight; 62 for (int i = 0; i < length; ++i) { 63 posX[i] = x + originX * widths[i]; 64 pos[i].set(posX[i], i ? pos[i - 1].y() + 3 : y + kTextHeight); 65 x += widths[i]; 66 } 67 68 canvas->drawPosTextH(text, length, posX, y, paint); 69 canvas->drawPosText(text, length, pos, paint); 70 } 71