michael@0: /* -*- Mode: Java; c-basic-offset: 4; tab-width: 20; indent-tabs-mode: nil; -*- michael@0: * This Source Code Form is subject to the terms of the Mozilla Public michael@0: * License, v. 2.0. If a copy of the MPL was not distributed with this michael@0: * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ michael@0: michael@0: package org.mozilla.gecko.gfx; michael@0: michael@0: import org.mozilla.gecko.mozglue.DirectBufferAllocator; michael@0: michael@0: import android.graphics.Bitmap; michael@0: import android.graphics.Canvas; michael@0: import android.graphics.Color; michael@0: import android.graphics.Paint; michael@0: import android.graphics.Typeface; michael@0: michael@0: import java.nio.ByteBuffer; michael@0: michael@0: /** michael@0: * Draws text on a layer. This is used for the frame rate meter. michael@0: */ michael@0: public class TextLayer extends SingleTileLayer { michael@0: private final ByteBuffer mBuffer; // this buffer is owned by the BufferedCairoImage michael@0: private final IntSize mSize; michael@0: michael@0: /* michael@0: * This awkward pattern is necessary due to Java's restrictions on when one can call superclass michael@0: * constructors. michael@0: */ michael@0: private TextLayer(ByteBuffer buffer, BufferedCairoImage image, IntSize size, String text) { michael@0: super(false, image); michael@0: mBuffer = buffer; michael@0: mSize = size; michael@0: renderText(text); michael@0: } michael@0: michael@0: public static TextLayer create(IntSize size, String text) { michael@0: ByteBuffer buffer = DirectBufferAllocator.allocate(size.width * size.height * 4); michael@0: BufferedCairoImage image = new BufferedCairoImage(buffer, size.width, size.height, michael@0: CairoImage.FORMAT_ARGB32); michael@0: return new TextLayer(buffer, image, size, text); michael@0: } michael@0: michael@0: public void setText(String text) { michael@0: renderText(text); michael@0: invalidate(); michael@0: } michael@0: michael@0: private void renderText(String text) { michael@0: Bitmap bitmap = Bitmap.createBitmap(mSize.width, mSize.height, Bitmap.Config.ARGB_8888); michael@0: Canvas canvas = new Canvas(bitmap); michael@0: michael@0: Paint textPaint = new Paint(); michael@0: textPaint.setAntiAlias(true); michael@0: textPaint.setColor(Color.WHITE); michael@0: textPaint.setFakeBoldText(true); michael@0: textPaint.setTextSize(18.0f); michael@0: textPaint.setTypeface(Typeface.DEFAULT_BOLD); michael@0: float width = textPaint.measureText(text) + 18.0f; michael@0: michael@0: Paint backgroundPaint = new Paint(); michael@0: backgroundPaint.setColor(Color.argb(127, 0, 0, 0)); michael@0: canvas.drawRect(0.0f, 0.0f, width, 18.0f + 6.0f, backgroundPaint); michael@0: michael@0: canvas.drawText(text, 6.0f, 18.0f, textPaint); michael@0: michael@0: bitmap.copyPixelsToBuffer(mBuffer.asIntBuffer()); michael@0: } michael@0: } michael@0: