|
1 /* -*- Mode: Java; c-basic-offset: 4; tab-width: 20; indent-tabs-mode: nil; -*- |
|
2 * This Source Code Form is subject to the terms of the Mozilla Public |
|
3 * License, v. 2.0. If a copy of the MPL was not distributed with this |
|
4 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ |
|
5 |
|
6 package org.mozilla.gecko.gfx; |
|
7 |
|
8 import org.mozilla.gecko.mozglue.DirectBufferAllocator; |
|
9 |
|
10 import android.graphics.Bitmap; |
|
11 import android.util.Log; |
|
12 |
|
13 import java.nio.ByteBuffer; |
|
14 |
|
15 /** A Cairo image that simply saves a buffer of pixel data. */ |
|
16 public class BufferedCairoImage extends CairoImage { |
|
17 private ByteBuffer mBuffer; |
|
18 private IntSize mSize; |
|
19 private int mFormat; |
|
20 |
|
21 private static String LOGTAG = "GeckoBufferedCairoImage"; |
|
22 |
|
23 /** Creates a buffered Cairo image from a byte buffer. */ |
|
24 public BufferedCairoImage(ByteBuffer inBuffer, int inWidth, int inHeight, int inFormat) { |
|
25 setBuffer(inBuffer, inWidth, inHeight, inFormat); |
|
26 } |
|
27 |
|
28 /** Creates a buffered Cairo image from an Android bitmap. */ |
|
29 public BufferedCairoImage(Bitmap bitmap) { |
|
30 setBitmap(bitmap); |
|
31 } |
|
32 |
|
33 private synchronized void freeBuffer() { |
|
34 mBuffer = DirectBufferAllocator.free(mBuffer); |
|
35 } |
|
36 |
|
37 @Override |
|
38 public void destroy() { |
|
39 try { |
|
40 freeBuffer(); |
|
41 } catch (Exception ex) { |
|
42 Log.e(LOGTAG, "error clearing buffer: ", ex); |
|
43 } |
|
44 } |
|
45 |
|
46 @Override |
|
47 public ByteBuffer getBuffer() { return mBuffer; } |
|
48 @Override |
|
49 public IntSize getSize() { return mSize; } |
|
50 @Override |
|
51 public int getFormat() { return mFormat; } |
|
52 |
|
53 |
|
54 public void setBuffer(ByteBuffer buffer, int width, int height, int format) { |
|
55 freeBuffer(); |
|
56 mBuffer = buffer; |
|
57 mSize = new IntSize(width, height); |
|
58 mFormat = format; |
|
59 } |
|
60 |
|
61 public void setBitmap(Bitmap bitmap) { |
|
62 mFormat = CairoUtils.bitmapConfigToCairoFormat(bitmap.getConfig()); |
|
63 mSize = new IntSize(bitmap.getWidth(), bitmap.getHeight()); |
|
64 |
|
65 int bpp = CairoUtils.bitsPerPixelForCairoFormat(mFormat); |
|
66 mBuffer = DirectBufferAllocator.allocate(mSize.getArea() * bpp); |
|
67 bitmap.copyPixelsToBuffer(mBuffer.asIntBuffer()); |
|
68 } |
|
69 } |