1 // Copyright 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "cc/font_atlas.h"
9 #include "base/string_split.h"
10 #include "third_party/skia/include/core/SkCanvas.h"
14 FontAtlas::FontAtlas(SkBitmap bitmap
, gfx::Rect asciiToRectTable
[128], int fontHeight
)
16 , m_fontHeight(fontHeight
)
18 for (size_t i
= 0; i
< 128; ++i
)
19 m_asciiToRectTable
[i
] = asciiToRectTable
[i
];
22 FontAtlas::~FontAtlas()
26 void FontAtlas::drawText(SkCanvas
* canvas
, const SkPaint
& paint
, const std::string
& text
, const gfx::Point
& destPosition
, const gfx::Size
& clip
) const
28 std::vector
<std::string
> lines
;
29 base::SplitString(text
, '\n', &lines
);
31 gfx::Point position
= destPosition
;
32 for (size_t i
= 0; i
< lines
.size(); ++i
) {
33 drawOneLineOfTextInternal(canvas
, paint
, lines
[i
], position
);
34 position
.set_y(position
.y() + m_fontHeight
);
35 if (position
.y() > clip
.height())
40 void FontAtlas::drawOneLineOfTextInternal(SkCanvas
* canvas
, const SkPaint
& paint
, const std::string
& textLine
, const gfx::Point
& destPosition
) const
42 gfx::Point position
= destPosition
;
43 for (unsigned i
= 0; i
< textLine
.length(); ++i
) {
44 // If the ASCII code is out of bounds, then index 0 is used, which is just a plain rectangle glyph.
45 int asciiIndex
= (textLine
[i
] < 128) ? textLine
[i
] : 0;
46 gfx::Rect glyphBounds
= m_asciiToRectTable
[asciiIndex
];
47 SkIRect source
= SkIRect::MakeXYWH(glyphBounds
.x(), glyphBounds
.y(), glyphBounds
.width(), glyphBounds
.height());
48 canvas
->drawBitmapRect(m_atlas
, &source
, SkRect::MakeXYWH(position
.x(), position
.y(), glyphBounds
.width(), glyphBounds
.height()), &paint
);
49 position
.set_x(position
.x() + glyphBounds
.width());
53 gfx::Size
FontAtlas::textSize(const std::string
& text
)
56 std::vector
<std::string
> lines
;
57 base::SplitString(text
, '\n', &lines
);
59 for (size_t i
= 0; i
< lines
.size(); ++i
) {
61 for (size_t j
= 0; j
< lines
[i
].size(); ++j
) {
62 int asciiIndex
= (lines
[i
][j
] < 128) ? lines
[i
][j
] : 0;
63 lineWidth
+= m_asciiToRectTable
[asciiIndex
].width();
65 if (lineWidth
> maxWidth
)
69 return gfx::Size(maxWidth
, m_fontHeight
* lines
.size());
72 void FontAtlas::drawDebugAtlas(SkCanvas
* canvas
, const gfx::Point
& destPosition
) const
74 SkIRect source
= SkIRect::MakeWH(m_atlas
.width(), m_atlas
.height());
75 canvas
->drawBitmapRect(m_atlas
, &source
, SkRect::MakeXYWH(destPosition
.x(), destPosition
.y(), m_atlas
.width(), m_atlas
.height()));