Canvas.java revision 96e240f25a97c10bba863df328ed73a82c34ff61
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.graphics;
18
19import android.text.TextUtils;
20import android.text.SpannedString;
21import android.text.SpannableString;
22import android.text.GraphicsOperations;
23import android.util.DisplayMetrics;
24
25import javax.microedition.khronos.opengles.GL;
26
27/**
28 * The Canvas class holds the "draw" calls. To draw something, you need
29 * 4 basic components: A Bitmap to hold the pixels, a Canvas to host
30 * the draw calls (writing into the bitmap), a drawing primitive (e.g. Rect,
31 * Path, text, Bitmap), and a paint (to describe the colors and styles for the
32 * drawing).
33 */
34public class Canvas {
35    // assigned in constructors, freed in finalizer
36    final int mNativeCanvas;
37
38    /*  Our native canvas can be either a raster, gl, or picture canvas.
39        If we are raster, then mGL will be null, and mBitmap may or may not be
40        present (our default constructor creates a raster canvas but no
41        java-bitmap is). If we are a gl-based, then mBitmap will be null, and
42        mGL will not be null. Thus both cannot be non-null, but its possible
43        for both to be null.
44    */
45    private Bitmap  mBitmap;    // if not null, mGL must be null
46    private GL      mGL;        // if not null, mBitmap must be null
47
48    // optional field set by the caller
49    private DrawFilter  mDrawFilter;
50
51    // Package-scoped for quick access.
52    /*package*/ int mDensity = Bitmap.DENSITY_NONE;
53
54    // Used by native code
55    @SuppressWarnings({"UnusedDeclaration"})
56    private int         mSurfaceFormat;
57
58    /**
59     * Construct an empty raster canvas. Use setBitmap() to specify a bitmap to
60     * draw into.  The initial target density is {@link Bitmap#DENSITY_NONE};
61     * this will typically be replaced when a target bitmap is set for the
62     * canvas.
63     */
64    public Canvas() {
65        // 0 means no native bitmap
66        mNativeCanvas = initRaster(0);
67    }
68
69    /**
70     * Construct a canvas with the specified bitmap to draw into. The bitmap
71     * must be mutable.
72     *
73     * <p>The initial target density of the canvas is the same as the given
74     * bitmap's density.
75     *
76     * @param bitmap Specifies a mutable bitmap for the canvas to draw into.
77     */
78    public Canvas(Bitmap bitmap) {
79        if (!bitmap.isMutable()) {
80            throw new IllegalStateException(
81                            "Immutable bitmap passed to Canvas constructor");
82        }
83        throwIfRecycled(bitmap);
84        mNativeCanvas = initRaster(bitmap.ni());
85        mBitmap = bitmap;
86        mDensity = bitmap.mDensity;
87    }
88
89    /*package*/ Canvas(int nativeCanvas) {
90        if (nativeCanvas == 0) {
91            throw new IllegalStateException();
92        }
93        mNativeCanvas = nativeCanvas;
94        mDensity = Bitmap.getDefaultDensity();
95    }
96
97    /**
98     * Construct a canvas with the specified gl context. All drawing through
99     * this canvas will be redirected to OpenGL. Note: some features may not
100     * be supported in this mode (e.g. some GL implementations may not support
101     * antialiasing or certain effects like ColorMatrix or certain Xfermodes).
102     * However, no exception will be thrown in those cases.
103     *
104     * <p>The initial target density of the canvas is the same as the initial
105     * density of bitmaps as per {@link Bitmap#getDensity() Bitmap.getDensity()}.
106     */
107    public Canvas(GL gl) {
108        mNativeCanvas = initGL();
109        mGL = gl;
110        mDensity = Bitmap.getDefaultDensity();
111    }
112
113    /**
114     * Return the GL object associated with this canvas, or null if it is not
115     * backed by GL.
116     */
117    public GL getGL() {
118        return mGL;
119    }
120
121    /**
122     * Call this to free up OpenGL resources that may be cached or allocated
123     * on behalf of the Canvas. Any subsequent drawing with a GL-backed Canvas
124     * will have to recreate those resources.
125     */
126    public static void freeGlCaches() {
127        freeCaches();
128    }
129
130    /**
131     * Specify a bitmap for the canvas to draw into.  As a side-effect, also
132     * updates the canvas's target density to match that of the bitmap.
133     *
134     * @param bitmap Specifies a mutable bitmap for the canvas to draw into.
135     *
136     * @see #setDensity(int)
137     * @see #getDensity()
138     */
139    public void setBitmap(Bitmap bitmap) {
140        if (!bitmap.isMutable()) {
141            throw new IllegalStateException();
142        }
143        if (mGL != null) {
144            throw new RuntimeException("Can't set a bitmap device on a GL canvas");
145        }
146        throwIfRecycled(bitmap);
147
148        native_setBitmap(mNativeCanvas, bitmap.ni());
149        mBitmap = bitmap;
150        mDensity = bitmap.mDensity;
151    }
152
153    /**
154     * Set the viewport dimensions if this canvas is GL based. If it is not,
155     * this method is ignored and no exception is thrown.
156     *
157     *  @param width    The width of the viewport
158     *  @param height   The height of the viewport
159     */
160    public void setViewport(int width, int height) {
161        if (mGL != null) {
162            nativeSetViewport(mNativeCanvas, width, height);
163        }
164    }
165
166    /**
167     * Return true if the device that the current layer draws into is opaque
168     * (i.e. does not support per-pixel alpha).
169     *
170     * @return true if the device that the current layer draws into is opaque
171     */
172    public native boolean isOpaque();
173
174    /**
175     * Returns the width of the current drawing layer
176     *
177     * @return the width of the current drawing layer
178     */
179    public native int getWidth();
180
181    /**
182     * Returns the height of the current drawing layer
183     *
184     * @return the height of the current drawing layer
185     */
186    public native int getHeight();
187
188    /**
189     * <p>Returns the target density of the canvas.  The default density is
190     * derived from the density of its backing bitmap, or
191     * {@link Bitmap#DENSITY_NONE} if there is not one.</p>
192     *
193     * @return Returns the current target density of the canvas, which is used
194     * to determine the scaling factor when drawing a bitmap into it.
195     *
196     * @see #setDensity(int)
197     * @see Bitmap#getDensity()
198     */
199    public int getDensity() {
200        return mDensity;
201    }
202
203    /**
204     * <p>Specifies the density for this Canvas' backing bitmap.  This modifies
205     * the target density of the canvas itself, as well as the density of its
206     * backing bitmap via {@link Bitmap#setDensity(int) Bitmap.setDensity(int)}.
207     *
208     * @param density The new target density of the canvas, which is used
209     * to determine the scaling factor when drawing a bitmap into it.  Use
210     * {@link Bitmap#DENSITY_NONE} to disable bitmap scaling.
211     *
212     * @see #getDensity()
213     * @see Bitmap#setDensity(int)
214     */
215    public void setDensity(int density) {
216        if (mBitmap != null) {
217            mBitmap.setDensity(density);
218        }
219        mDensity = density;
220    }
221
222    // the SAVE_FLAG constants must match their native equivalents
223
224    /** restore the current matrix when restore() is called */
225    public static final int MATRIX_SAVE_FLAG = 0x01;
226    /** restore the current clip when restore() is called */
227    public static final int CLIP_SAVE_FLAG = 0x02;
228    /** the layer needs to per-pixel alpha */
229    public static final int HAS_ALPHA_LAYER_SAVE_FLAG = 0x04;
230    /** the layer needs to 8-bits per color component */
231    public static final int FULL_COLOR_LAYER_SAVE_FLAG = 0x08;
232    /** clip against the layer's bounds */
233    public static final int CLIP_TO_LAYER_SAVE_FLAG = 0x10;
234    /** restore everything when restore() is called */
235    public static final int ALL_SAVE_FLAG = 0x1F;
236
237    /**
238     * Saves the current matrix and clip onto a private stack. Subsequent
239     * calls to translate,scale,rotate,skew,concat or clipRect,clipPath
240     * will all operate as usual, but when the balancing call to restore()
241     * is made, those calls will be forgotten, and the settings that existed
242     * before the save() will be reinstated.
243     *
244     * @return The value to pass to restoreToCount() to balance this save()
245     */
246    public native int save();
247
248    /**
249     * Based on saveFlags, can save the current matrix and clip onto a private
250     * stack. Subsequent calls to translate,scale,rotate,skew,concat or
251     * clipRect,clipPath will all operate as usual, but when the balancing
252     * call to restore() is made, those calls will be forgotten, and the
253     * settings that existed before the save() will be reinstated.
254     *
255     * @param saveFlags flag bits that specify which parts of the Canvas state
256     *                  to save/restore
257     * @return The value to pass to restoreToCount() to balance this save()
258     */
259    public native int save(int saveFlags);
260
261    /**
262     * This behaves the same as save(), but in addition it allocates an
263     * offscreen bitmap. All drawing calls are directed there, and only when
264     * the balancing call to restore() is made is that offscreen transfered to
265     * the canvas (or the previous layer). Subsequent calls to translate,
266     * scale, rotate, skew, concat or clipRect, clipPath all operate on this
267     * copy. When the balancing call to restore() is made, this copy is
268     * deleted and the previous matrix/clip state is restored.
269     *
270     * @param bounds May be null. The maximum size the offscreen bitmap
271     *               needs to be (in local coordinates)
272     * @param paint  This is copied, and is applied to the offscreen when
273     *               restore() is called.
274     * @param saveFlags  see _SAVE_FLAG constants
275     * @return       value to pass to restoreToCount() to balance this save()
276     */
277    public int saveLayer(RectF bounds, Paint paint, int saveFlags) {
278        return native_saveLayer(mNativeCanvas, bounds,
279                                paint != null ? paint.mNativePaint : 0,
280                                saveFlags);
281    }
282
283    /**
284     * Helper version of saveLayer() that takes 4 values rather than a RectF.
285     */
286    public int saveLayer(float left, float top, float right, float bottom,
287                         Paint paint, int saveFlags) {
288        return native_saveLayer(mNativeCanvas, left, top, right, bottom,
289                                paint != null ? paint.mNativePaint : 0,
290                                saveFlags);
291    }
292
293    /**
294     * This behaves the same as save(), but in addition it allocates an
295     * offscreen bitmap. All drawing calls are directed there, and only when
296     * the balancing call to restore() is made is that offscreen transfered to
297     * the canvas (or the previous layer). Subsequent calls to translate,
298     * scale, rotate, skew, concat or clipRect, clipPath all operate on this
299     * copy. When the balancing call to restore() is made, this copy is
300     * deleted and the previous matrix/clip state is restored.
301     *
302     * @param bounds    The maximum size the offscreen bitmap needs to be
303     *                  (in local coordinates)
304     * @param alpha     The alpha to apply to the offscreen when when it is
305                        drawn during restore()
306     * @param saveFlags see _SAVE_FLAG constants
307     * @return          value to pass to restoreToCount() to balance this call
308     */
309    public int saveLayerAlpha(RectF bounds, int alpha, int saveFlags) {
310        alpha = Math.min(255, Math.max(0, alpha));
311        return native_saveLayerAlpha(mNativeCanvas, bounds, alpha, saveFlags);
312    }
313
314    /**
315     * Helper for saveLayerAlpha() that takes 4 values instead of a RectF.
316     */
317    public int saveLayerAlpha(float left, float top, float right, float bottom,
318                              int alpha, int saveFlags) {
319        return native_saveLayerAlpha(mNativeCanvas, left, top, right, bottom,
320                                     alpha, saveFlags);
321    }
322
323    /**
324     * This call balances a previous call to save(), and is used to remove all
325     * modifications to the matrix/clip state since the last save call. It is
326     * an error to call restore() more times than save() was called.
327     */
328    public native void restore();
329
330    /**
331     * Returns the number of matrix/clip states on the Canvas' private stack.
332     * This will equal # save() calls - # restore() calls.
333     */
334    public native int getSaveCount();
335
336    /**
337     * Efficient way to pop any calls to save() that happened after the save
338     * count reached saveCount. It is an error for saveCount to be less than 1.
339     *
340     * Example:
341     *    int count = canvas.save();
342     *    ... // more calls potentially to save()
343     *    canvas.restoreToCount(count);
344     *    // now the canvas is back in the same state it was before the initial
345     *    // call to save().
346     *
347     * @param saveCount The save level to restore to.
348     */
349    public native void restoreToCount(int saveCount);
350
351    /**
352     * Preconcat the current matrix with the specified translation
353     *
354     * @param dx The distance to translate in X
355     * @param dy The distance to translate in Y
356    */
357    public native void translate(float dx, float dy);
358
359    /**
360     * Preconcat the current matrix with the specified scale.
361     *
362     * @param sx The amount to scale in X
363     * @param sy The amount to scale in Y
364     */
365    public native void scale(float sx, float sy);
366
367    /**
368     * Preconcat the current matrix with the specified scale.
369     *
370     * @param sx The amount to scale in X
371     * @param sy The amount to scale in Y
372     * @param px The x-coord for the pivot point (unchanged by the rotation)
373     * @param py The y-coord for the pivot point (unchanged by the rotation)
374     */
375    public final void scale(float sx, float sy, float px, float py) {
376        translate(px, py);
377        scale(sx, sy);
378        translate(-px, -py);
379    }
380
381    /**
382     * Preconcat the current matrix with the specified rotation.
383     *
384     * @param degrees The amount to rotate, in degrees
385     */
386    public native void rotate(float degrees);
387
388    /**
389     * Preconcat the current matrix with the specified rotation.
390     *
391     * @param degrees The amount to rotate, in degrees
392     * @param px The x-coord for the pivot point (unchanged by the rotation)
393     * @param py The y-coord for the pivot point (unchanged by the rotation)
394     */
395    public final void rotate(float degrees, float px, float py) {
396        translate(px, py);
397        rotate(degrees);
398        translate(-px, -py);
399    }
400
401    /**
402     * Preconcat the current matrix with the specified skew.
403     *
404     * @param sx The amount to skew in X
405     * @param sy The amount to skew in Y
406     */
407    public native void skew(float sx, float sy);
408
409    /**
410     * Preconcat the current matrix with the specified matrix.
411     *
412     * @param matrix The matrix to preconcatenate with the current matrix
413     */
414    public void concat(Matrix matrix) {
415        native_concat(mNativeCanvas, matrix.native_instance);
416    }
417
418    /**
419     * Completely replace the current matrix with the specified matrix. If the
420     * matrix parameter is null, then the current matrix is reset to identity.
421     *
422     * @param matrix The matrix to replace the current matrix with. If it is
423     *               null, set the current matrix to identity.
424     */
425    public void setMatrix(Matrix matrix) {
426        native_setMatrix(mNativeCanvas,
427                         matrix == null ? 0 : matrix.native_instance);
428    }
429
430    /**
431     * Return, in ctm, the current transformation matrix. This does not alter
432     * the matrix in the canvas, but just returns a copy of it.
433     */
434    public void getMatrix(Matrix ctm) {
435        native_getCTM(mNativeCanvas, ctm.native_instance);
436    }
437
438    /**
439     * Return a new matrix with a copy of the canvas' current transformation
440     * matrix.
441     */
442    public final Matrix getMatrix() {
443        Matrix m = new Matrix();
444        getMatrix(m);
445        return m;
446    }
447
448    /**
449     * Modify the current clip with the specified rectangle.
450     *
451     * @param rect The rect to intersect with the current clip
452     * @param op How the clip is modified
453     * @return true if the resulting clip is non-empty
454     */
455    public boolean clipRect(RectF rect, Region.Op op) {
456        return native_clipRect(mNativeCanvas,
457                               rect.left, rect.top, rect.right, rect.bottom,
458                               op.nativeInt);
459    }
460
461    /**
462     * Modify the current clip with the specified rectangle, which is
463     * expressed in local coordinates.
464     *
465     * @param rect The rectangle to intersect with the current clip.
466     * @param op How the clip is modified
467     * @return true if the resulting clip is non-empty
468     */
469    public boolean clipRect(Rect rect, Region.Op op) {
470        return native_clipRect(mNativeCanvas,
471                               rect.left, rect.top, rect.right, rect.bottom,
472                               op.nativeInt);
473    }
474
475    /**
476     * Intersect the current clip with the specified rectangle, which is
477     * expressed in local coordinates.
478     *
479     * @param rect The rectangle to intersect with the current clip.
480     * @return true if the resulting clip is non-empty
481     */
482    public native boolean clipRect(RectF rect);
483
484    /**
485     * Intersect the current clip with the specified rectangle, which is
486     * expressed in local coordinates.
487     *
488     * @param rect The rectangle to intersect with the current clip.
489     * @return true if the resulting clip is non-empty
490     */
491    public native boolean clipRect(Rect rect);
492
493    /**
494     * Modify the current clip with the specified rectangle, which is
495     * expressed in local coordinates.
496     *
497     * @param left   The left side of the rectangle to intersect with the
498     *               current clip
499     * @param top    The top of the rectangle to intersect with the current
500     *               clip
501     * @param right  The right side of the rectangle to intersect with the
502     *               current clip
503     * @param bottom The bottom of the rectangle to intersect with the current
504     *               clip
505     * @param op     How the clip is modified
506     * @return       true if the resulting clip is non-empty
507     */
508    public boolean clipRect(float left, float top, float right, float bottom,
509                            Region.Op op) {
510        return native_clipRect(mNativeCanvas, left, top, right, bottom,
511                               op.nativeInt);
512    }
513
514    /**
515     * Intersect the current clip with the specified rectangle, which is
516     * expressed in local coordinates.
517     *
518     * @param left   The left side of the rectangle to intersect with the
519     *               current clip
520     * @param top    The top of the rectangle to intersect with the current clip
521     * @param right  The right side of the rectangle to intersect with the
522     *               current clip
523     * @param bottom The bottom of the rectangle to intersect with the current
524     *               clip
525     * @return       true if the resulting clip is non-empty
526     */
527    public native boolean clipRect(float left, float top,
528                                   float right, float bottom);
529
530    /**
531     * Intersect the current clip with the specified rectangle, which is
532     * expressed in local coordinates.
533     *
534     * @param left   The left side of the rectangle to intersect with the
535     *               current clip
536     * @param top    The top of the rectangle to intersect with the current clip
537     * @param right  The right side of the rectangle to intersect with the
538     *               current clip
539     * @param bottom The bottom of the rectangle to intersect with the current
540     *               clip
541     * @return       true if the resulting clip is non-empty
542     */
543    public native boolean clipRect(int left, int top,
544                                   int right, int bottom);
545
546    /**
547        * Modify the current clip with the specified path.
548     *
549     * @param path The path to operate on the current clip
550     * @param op   How the clip is modified
551     * @return     true if the resulting is non-empty
552     */
553    public boolean clipPath(Path path, Region.Op op) {
554        return native_clipPath(mNativeCanvas, path.ni(), op.nativeInt);
555    }
556
557    /**
558     * Intersect the current clip with the specified path.
559     *
560     * @param path The path to intersect with the current clip
561     * @return     true if the resulting is non-empty
562     */
563    public boolean clipPath(Path path) {
564        return clipPath(path, Region.Op.INTERSECT);
565    }
566
567    /**
568     * Modify the current clip with the specified region. Note that unlike
569     * clipRect() and clipPath() which transform their arguments by the
570     * current matrix, clipRegion() assumes its argument is already in the
571     * coordinate system of the current layer's bitmap, and so not
572     * transformation is performed.
573     *
574     * @param region The region to operate on the current clip, based on op
575     * @param op How the clip is modified
576     * @return true if the resulting is non-empty
577     */
578    public boolean clipRegion(Region region, Region.Op op) {
579        return native_clipRegion(mNativeCanvas, region.ni(), op.nativeInt);
580    }
581
582    /**
583     * Intersect the current clip with the specified region. Note that unlike
584     * clipRect() and clipPath() which transform their arguments by the
585     * current matrix, clipRegion() assumes its argument is already in the
586     * coordinate system of the current layer's bitmap, and so not
587     * transformation is performed.
588     *
589     * @param region The region to operate on the current clip, based on op
590     * @return true if the resulting is non-empty
591     */
592    public boolean clipRegion(Region region) {
593        return clipRegion(region, Region.Op.INTERSECT);
594    }
595
596    public DrawFilter getDrawFilter() {
597        return mDrawFilter;
598    }
599
600    public void setDrawFilter(DrawFilter filter) {
601        int nativeFilter = 0;
602        if (filter != null) {
603            nativeFilter = filter.mNativeInt;
604        }
605        mDrawFilter = filter;
606        nativeSetDrawFilter(mNativeCanvas, nativeFilter);
607    }
608
609    public enum EdgeType {
610        BW(0),  //!< treat edges by just rounding to nearest pixel boundary
611        AA(1);  //!< treat edges by rounding-out, since they may be antialiased
612
613        EdgeType(int nativeInt) {
614            this.nativeInt = nativeInt;
615        }
616        final int nativeInt;
617    }
618
619    /**
620     * Return true if the specified rectangle, after being transformed by the
621     * current matrix, would lie completely outside of the current clip. Call
622     * this to check if an area you intend to draw into is clipped out (and
623     * therefore you can skip making the draw calls).
624     *
625     * @param rect  the rect to compare with the current clip
626     * @param type  specifies how to treat the edges (BW or antialiased)
627     * @return      true if the rect (transformed by the canvas' matrix)
628     *              does not intersect with the canvas' clip
629     */
630    public boolean quickReject(RectF rect, EdgeType type) {
631        return native_quickReject(mNativeCanvas, rect, type.nativeInt);
632    }
633
634    /**
635     * Return true if the specified path, after being transformed by the
636     * current matrix, would lie completely outside of the current clip. Call
637     * this to check if an area you intend to draw into is clipped out (and
638     * therefore you can skip making the draw calls). Note: for speed it may
639     * return false even if the path itself might not intersect the clip
640     * (i.e. the bounds of the path intersects, but the path does not).
641     *
642     * @param path        The path to compare with the current clip
643     * @param type        true if the path should be considered antialiased,
644     *                    since that means it may
645     *                    affect a larger area (more pixels) than
646     *                    non-antialiased.
647     * @return            true if the path (transformed by the canvas' matrix)
648     *                    does not intersect with the canvas' clip
649     */
650    public boolean quickReject(Path path, EdgeType type) {
651        return native_quickReject(mNativeCanvas, path.ni(), type.nativeInt);
652    }
653
654    /**
655     * Return true if the specified rectangle, after being transformed by the
656     * current matrix, would lie completely outside of the current clip. Call
657     * this to check if an area you intend to draw into is clipped out (and
658     * therefore you can skip making the draw calls).
659     *
660     * @param left        The left side of the rectangle to compare with the
661     *                    current clip
662     * @param top         The top of the rectangle to compare with the current
663     *                    clip
664     * @param right       The right side of the rectangle to compare with the
665     *                    current clip
666     * @param bottom      The bottom of the rectangle to compare with the
667     *                    current clip
668     * @param type        true if the rect should be considered antialiased,
669     *                    since that means it may affect a larger area (more
670     *                    pixels) than non-antialiased.
671     * @return            true if the rect (transformed by the canvas' matrix)
672     *                    does not intersect with the canvas' clip
673     */
674    public boolean quickReject(float left, float top, float right, float bottom,
675                               EdgeType type) {
676        return native_quickReject(mNativeCanvas, left, top, right, bottom,
677                                  type.nativeInt);
678    }
679
680    /**
681     * Retrieve the clip bounds, returning true if they are non-empty.
682     *
683     * @param bounds Return the clip bounds here. If it is null, ignore it but
684     *               still return true if the current clip is non-empty.
685     * @return true if the current clip is non-empty.
686     */
687    public boolean getClipBounds(Rect bounds) {
688        return native_getClipBounds(mNativeCanvas, bounds);
689    }
690
691    /**
692     * Retrieve the clip bounds.
693     *
694     * @return the clip bounds, or [0, 0, 0, 0] if the clip is empty.
695     */
696    public final Rect getClipBounds() {
697        Rect r = new Rect();
698        getClipBounds(r);
699        return r;
700    }
701
702    /**
703     * Fill the entire canvas' bitmap (restricted to the current clip) with the
704     * specified RGB color, using srcover porterduff mode.
705     *
706     * @param r red component (0..255) of the color to draw onto the canvas
707     * @param g green component (0..255) of the color to draw onto the canvas
708     * @param b blue component (0..255) of the color to draw onto the canvas
709     */
710    public void drawRGB(int r, int g, int b) {
711        native_drawRGB(mNativeCanvas, r, g, b);
712    }
713
714    /**
715     * Fill the entire canvas' bitmap (restricted to the current clip) with the
716     * specified ARGB color, using srcover porterduff mode.
717     *
718     * @param a alpha component (0..255) of the color to draw onto the canvas
719     * @param r red component (0..255) of the color to draw onto the canvas
720     * @param g green component (0..255) of the color to draw onto the canvas
721     * @param b blue component (0..255) of the color to draw onto the canvas
722     */
723    public void drawARGB(int a, int r, int g, int b) {
724        native_drawARGB(mNativeCanvas, a, r, g, b);
725    }
726
727    /**
728     * Fill the entire canvas' bitmap (restricted to the current clip) with the
729     * specified color, using srcover porterduff mode.
730     *
731     * @param color the color to draw onto the canvas
732     */
733    public void drawColor(int color) {
734        native_drawColor(mNativeCanvas, color);
735    }
736
737    /**
738     * Fill the entire canvas' bitmap (restricted to the current clip) with the
739     * specified color and porter-duff xfermode.
740     *
741     * @param color the color to draw with
742     * @param mode  the porter-duff mode to apply to the color
743     */
744    public void drawColor(int color, PorterDuff.Mode mode) {
745        native_drawColor(mNativeCanvas, color, mode.nativeInt);
746    }
747
748    /**
749     * Fill the entire canvas' bitmap (restricted to the current clip) with
750     * the specified paint. This is equivalent (but faster) to drawing an
751     * infinitely large rectangle with the specified paint.
752     *
753     * @param paint The paint used to draw onto the canvas
754     */
755    public void drawPaint(Paint paint) {
756        native_drawPaint(mNativeCanvas, paint.mNativePaint);
757    }
758
759    /**
760     * Draw a series of points. Each point is centered at the coordinate
761     * specified by pts[], and its diameter is specified by the paint's stroke
762     * width (as transformed by the canvas' CTM), with special treatment for
763     * a stroke width of 0, which always draws exactly 1 pixel (or at most 4
764     * if antialiasing is enabled). The shape of the point is controlled by
765     * the paint's Cap type. The shape is a square, unless the cap type is
766     * Round, in which case the shape is a circle.
767     *
768     * @param pts      Array of points to draw [x0 y0 x1 y1 x2 y2 ...]
769     * @param offset   Number of values to skip before starting to draw.
770     * @param count    The number of values to process, after skipping offset
771     *                 of them. Since one point uses two values, the number of
772     *                 "points" that are drawn is really (count >> 1).
773     * @param paint    The paint used to draw the points
774     */
775    public native void drawPoints(float[] pts, int offset, int count,
776                                  Paint paint);
777
778    /**
779     * Helper for drawPoints() that assumes you want to draw the entire array
780     */
781    public void drawPoints(float[] pts, Paint paint) {
782        drawPoints(pts, 0, pts.length, paint);
783    }
784
785    /**
786     * Helper for drawPoints() for drawing a single point.
787     */
788    public native void drawPoint(float x, float y, Paint paint);
789
790    /**
791     * Draw a line segment with the specified start and stop x,y coordinates,
792     * using the specified paint. NOTE: since a line is always "framed", the
793     * Style is ignored in the paint.
794     *
795     * @param startX The x-coordinate of the start point of the line
796     * @param startY The y-coordinate of the start point of the line
797     * @param paint  The paint used to draw the line
798     */
799    public void drawLine(float startX, float startY, float stopX, float stopY,
800                         Paint paint) {
801        native_drawLine(mNativeCanvas, startX, startY, stopX, stopY,
802                        paint.mNativePaint);
803    }
804
805    /**
806     * Draw a series of lines. Each line is taken from 4 consecutive values
807     * in the pts array. Thus to draw 1 line, the array must contain at least 4
808     * values. This is logically the same as drawing the array as follows:
809     * drawLine(pts[0], pts[1], pts[2], pts[3]) followed by
810     * drawLine(pts[4], pts[5], pts[6], pts[7]) and so on.
811     *
812     * @param pts      Array of points to draw [x0 y0 x1 y1 x2 y2 ...]
813     * @param offset   Number of values in the array to skip before drawing.
814     * @param count    The number of values in the array to process, after
815     *                 skipping "offset" of them. Since each line uses 4 values,
816     *                 the number of "lines" that are drawn is really
817     *                 (count >> 2).
818     * @param paint    The paint used to draw the points
819     */
820    public native void drawLines(float[] pts, int offset, int count,
821                                 Paint paint);
822
823    public void drawLines(float[] pts, Paint paint) {
824        drawLines(pts, 0, pts.length, paint);
825    }
826
827    /**
828     * Draw the specified Rect using the specified paint. The rectangle will
829     * be filled or framed based on the Style in the paint.
830     *
831     * @param rect  The rect to be drawn
832     * @param paint The paint used to draw the rect
833     */
834    public void drawRect(RectF rect, Paint paint) {
835        native_drawRect(mNativeCanvas, rect, paint.mNativePaint);
836    }
837
838    /**
839     * Draw the specified Rect using the specified Paint. The rectangle
840     * will be filled or framed based on the Style in the paint.
841     *
842     * @param r        The rectangle to be drawn.
843     * @param paint    The paint used to draw the rectangle
844     */
845    public void drawRect(Rect r, Paint paint) {
846        drawRect(r.left, r.top, r.right, r.bottom, paint);
847    }
848
849
850    /**
851     * Draw the specified Rect using the specified paint. The rectangle will
852     * be filled or framed based on the Style in the paint.
853     *
854     * @param left   The left side of the rectangle to be drawn
855     * @param top    The top side of the rectangle to be drawn
856     * @param right  The right side of the rectangle to be drawn
857     * @param bottom The bottom side of the rectangle to be drawn
858     * @param paint  The paint used to draw the rect
859     */
860    public void drawRect(float left, float top, float right, float bottom,
861                         Paint paint) {
862        native_drawRect(mNativeCanvas, left, top, right, bottom,
863                        paint.mNativePaint);
864    }
865
866    /**
867     * Draw the specified oval using the specified paint. The oval will be
868     * filled or framed based on the Style in the paint.
869     *
870     * @param oval The rectangle bounds of the oval to be drawn
871     */
872    public void drawOval(RectF oval, Paint paint) {
873        if (oval == null) {
874            throw new NullPointerException();
875        }
876        native_drawOval(mNativeCanvas, oval, paint.mNativePaint);
877    }
878
879    /**
880     * Draw the specified circle using the specified paint. If radius is <= 0,
881     * then nothing will be drawn. The circle will be filled or framed based
882     * on the Style in the paint.
883     *
884     * @param cx     The x-coordinate of the center of the cirle to be drawn
885     * @param cy     The y-coordinate of the center of the cirle to be drawn
886     * @param radius The radius of the cirle to be drawn
887     * @param paint  The paint used to draw the circle
888     */
889    public void drawCircle(float cx, float cy, float radius, Paint paint) {
890        native_drawCircle(mNativeCanvas, cx, cy, radius,
891                          paint.mNativePaint);
892    }
893
894    /**
895     * Draw the specified arc, which will be scaled to fit inside the
896     * specified oval. If the sweep angle is >= 360, then the oval is drawn
897     * completely. Note that this differs slightly from SkPath::arcTo, which
898     * treats the sweep angle mod 360.
899     *
900     * @param oval       The bounds of oval used to define the shape and size
901     *                   of the arc
902     * @param startAngle Starting angle (in degrees) where the arc begins
903     * @param sweepAngle Sweep angle (in degrees) measured clockwise
904     * @param useCenter If true, include the center of the oval in the arc, and
905                        close it if it is being stroked. This will draw a wedge
906     * @param paint      The paint used to draw the arc
907     */
908    public void drawArc(RectF oval, float startAngle, float sweepAngle,
909                        boolean useCenter, Paint paint) {
910        if (oval == null) {
911            throw new NullPointerException();
912        }
913        native_drawArc(mNativeCanvas, oval, startAngle, sweepAngle,
914                       useCenter, paint.mNativePaint);
915    }
916
917    /**
918     * Draw the specified round-rect using the specified paint. The roundrect
919     * will be filled or framed based on the Style in the paint.
920     *
921     * @param rect  The rectangular bounds of the roundRect to be drawn
922     * @param rx    The x-radius of the oval used to round the corners
923     * @param ry    The y-radius of the oval used to round the corners
924     * @param paint The paint used to draw the roundRect
925     */
926    public void drawRoundRect(RectF rect, float rx, float ry, Paint paint) {
927        if (rect == null) {
928            throw new NullPointerException();
929        }
930        native_drawRoundRect(mNativeCanvas, rect, rx, ry,
931                             paint.mNativePaint);
932    }
933
934    /**
935     * Draw the specified path using the specified paint. The path will be
936     * filled or framed based on the Style in the paint.
937     *
938     * @param path  The path to be drawn
939     * @param paint The paint used to draw the path
940     */
941    public void drawPath(Path path, Paint paint) {
942        native_drawPath(mNativeCanvas, path.ni(), paint.mNativePaint);
943    }
944
945    private static void throwIfRecycled(Bitmap bitmap) {
946        if (bitmap.isRecycled()) {
947            throw new RuntimeException(
948                        "Canvas: trying to use a recycled bitmap " + bitmap);
949        }
950    }
951
952    /**
953     * Draw the specified bitmap, with its top/left corner at (x,y), using
954     * the specified paint, transformed by the current matrix.
955     *
956     * <p>Note: if the paint contains a maskfilter that generates a mask which
957     * extends beyond the bitmap's original width/height (e.g. BlurMaskFilter),
958     * then the bitmap will be drawn as if it were in a Shader with CLAMP mode.
959     * Thus the color outside of the original width/height will be the edge
960     * color replicated.
961     *
962     * <p>If the bitmap and canvas have different densities, this function
963     * will take care of automatically scaling the bitmap to draw at the
964     * same density as the canvas.
965     *
966     * @param bitmap The bitmap to be drawn
967     * @param left   The position of the left side of the bitmap being drawn
968     * @param top    The position of the top side of the bitmap being drawn
969     * @param paint  The paint used to draw the bitmap (may be null)
970     */
971    public void drawBitmap(Bitmap bitmap, float left, float top, Paint paint) {
972        throwIfRecycled(bitmap);
973        native_drawBitmap(mNativeCanvas, bitmap.ni(), left, top,
974                paint != null ? paint.mNativePaint : 0, mDensity, bitmap.mDensity);
975    }
976
977    /**
978     * Draw the specified bitmap, scaling/translating automatically to fill
979     * the destination rectangle. If the source rectangle is not null, it
980     * specifies the subset of the bitmap to draw.
981     *
982     * <p>Note: if the paint contains a maskfilter that generates a mask which
983     * extends beyond the bitmap's original width/height (e.g. BlurMaskFilter),
984     * then the bitmap will be drawn as if it were in a Shader with CLAMP mode.
985     * Thus the color outside of the original width/height will be the edge
986     * color replicated.
987     *
988     * <p>This function <em>ignores the density associated with the bitmap</em>.
989     * This is because the source and destination rectangle coordinate
990     * spaces are in their respective densities, so must already have the
991     * appropriate scaling factor applied.
992     *
993     * @param bitmap The bitmap to be drawn
994     * @param src    May be null. The subset of the bitmap to be drawn
995     * @param dst    The rectangle that the bitmap will be scaled/translated
996     *               to fit into
997     * @param paint  May be null. The paint used to draw the bitmap
998     */
999    public void drawBitmap(Bitmap bitmap, Rect src, RectF dst, Paint paint) {
1000        if (dst == null) {
1001            throw new NullPointerException();
1002        }
1003        throwIfRecycled(bitmap);
1004        native_drawBitmap(mNativeCanvas, bitmap.ni(), src, dst,
1005                          paint != null ? paint.mNativePaint : 0);
1006    }
1007
1008    /**
1009     * Draw the specified bitmap, scaling/translating automatically to fill
1010     * the destination rectangle. If the source rectangle is not null, it
1011     * specifies the subset of the bitmap to draw.
1012     *
1013     * <p>Note: if the paint contains a maskfilter that generates a mask which
1014     * extends beyond the bitmap's original width/height (e.g. BlurMaskFilter),
1015     * then the bitmap will be drawn as if it were in a Shader with CLAMP mode.
1016     * Thus the color outside of the original width/height will be the edge
1017     * color replicated.
1018     *
1019     * <p>This function <em>ignores the density associated with the bitmap</em>.
1020     * This is because the source and destination rectangle coordinate
1021     * spaces are in their respective densities, so must already have the
1022     * appropriate scaling factor applied.
1023     *
1024     * @param bitmap The bitmap to be drawn
1025     * @param src    May be null. The subset of the bitmap to be drawn
1026     * @param dst    The rectangle that the bitmap will be scaled/translated
1027     *               to fit into
1028     * @param paint  May be null. The paint used to draw the bitmap
1029     */
1030    public void drawBitmap(Bitmap bitmap, Rect src, Rect dst, Paint paint) {
1031        if (dst == null) {
1032            throw new NullPointerException();
1033        }
1034        throwIfRecycled(bitmap);
1035        native_drawBitmap(mNativeCanvas, bitmap.ni(), src, dst,
1036                          paint != null ? paint.mNativePaint : 0);
1037    }
1038
1039    /**
1040     * Treat the specified array of colors as a bitmap, and draw it. This gives
1041     * the same result as first creating a bitmap from the array, and then
1042     * drawing it, but this method avoids explicitly creating a bitmap object
1043     * which can be more efficient if the colors are changing often.
1044     *
1045     * @param colors Array of colors representing the pixels of the bitmap
1046     * @param offset Offset into the array of colors for the first pixel
1047     * @param stride The number of of colors in the array between rows (must be
1048     *               >= width or <= -width).
1049     * @param x The X coordinate for where to draw the bitmap
1050     * @param y The Y coordinate for where to draw the bitmap
1051     * @param width The width of the bitmap
1052     * @param height The height of the bitmap
1053     * @param hasAlpha True if the alpha channel of the colors contains valid
1054     *                 values. If false, the alpha byte is ignored (assumed to
1055     *                 be 0xFF for every pixel).
1056     * @param paint  May be null. The paint used to draw the bitmap
1057     */
1058    public void drawBitmap(int[] colors, int offset, int stride, float x,
1059                           float y, int width, int height, boolean hasAlpha,
1060                           Paint paint) {
1061        // check for valid input
1062        if (width < 0) {
1063            throw new IllegalArgumentException("width must be >= 0");
1064        }
1065        if (height < 0) {
1066            throw new IllegalArgumentException("height must be >= 0");
1067        }
1068        if (Math.abs(stride) < width) {
1069            throw new IllegalArgumentException("abs(stride) must be >= width");
1070        }
1071        int lastScanline = offset + (height - 1) * stride;
1072        int length = colors.length;
1073        if (offset < 0 || (offset + width > length) || lastScanline < 0
1074                || (lastScanline + width > length)) {
1075            throw new ArrayIndexOutOfBoundsException();
1076        }
1077        // quick escape if there's nothing to draw
1078        if (width == 0 || height == 0) {
1079            return;
1080        }
1081        // punch down to native for the actual draw
1082        native_drawBitmap(mNativeCanvas, colors, offset, stride, x, y, width, height, hasAlpha,
1083                paint != null ? paint.mNativePaint : 0);
1084    }
1085
1086    /** Legacy version of drawBitmap(int[] colors, ...) that took ints for x,y
1087     */
1088    public void drawBitmap(int[] colors, int offset, int stride, int x, int y,
1089                           int width, int height, boolean hasAlpha,
1090                           Paint paint) {
1091        // call through to the common float version
1092        drawBitmap(colors, offset, stride, (float)x, (float)y, width, height,
1093                   hasAlpha, paint);
1094    }
1095
1096    /**
1097     * Draw the bitmap using the specified matrix.
1098     *
1099     * @param bitmap The bitmap to draw
1100     * @param matrix The matrix used to transform the bitmap when it is drawn
1101     * @param paint  May be null. The paint used to draw the bitmap
1102     */
1103    public void drawBitmap(Bitmap bitmap, Matrix matrix, Paint paint) {
1104        nativeDrawBitmapMatrix(mNativeCanvas, bitmap.ni(), matrix.ni(),
1105                paint != null ? paint.mNativePaint : 0);
1106    }
1107
1108    private static void checkRange(int length, int offset, int count) {
1109        if ((offset | count) < 0 || offset + count > length) {
1110            throw new ArrayIndexOutOfBoundsException();
1111        }
1112    }
1113
1114    /**
1115     * Draw the bitmap through the mesh, where mesh vertices are evenly
1116     * distributed across the bitmap. There are meshWidth+1 vertices across, and
1117     * meshHeight+1 vertices down. The verts array is accessed in row-major
1118     * order, so that the first meshWidth+1 vertices are distributed across the
1119     * top of the bitmap from left to right. A more general version of this
1120     * methid is drawVertices().
1121     *
1122     * @param bitmap The bitmap to draw using the mesh
1123     * @param meshWidth The number of columns in the mesh. Nothing is drawn if
1124     *                  this is 0
1125     * @param meshHeight The number of rows in the mesh. Nothing is drawn if
1126     *                   this is 0
1127     * @param verts Array of x,y pairs, specifying where the mesh should be
1128     *              drawn. There must be at least
1129     *              (meshWidth+1) * (meshHeight+1) * 2 + meshOffset values
1130     *              in the array
1131     * @param vertOffset Number of verts elements to skip before drawing
1132     * @param colors May be null. Specifies a color at each vertex, which is
1133     *               interpolated across the cell, and whose values are
1134     *               multiplied by the corresponding bitmap colors. If not null,
1135     *               there must be at least (meshWidth+1) * (meshHeight+1) +
1136     *               colorOffset values in the array.
1137     * @param colorOffset Number of color elements to skip before drawing
1138     * @param paint  May be null. The paint used to draw the bitmap
1139     */
1140    public void drawBitmapMesh(Bitmap bitmap, int meshWidth, int meshHeight,
1141                               float[] verts, int vertOffset,
1142                               int[] colors, int colorOffset, Paint paint) {
1143        if ((meshWidth | meshHeight | vertOffset | colorOffset) < 0) {
1144            throw new ArrayIndexOutOfBoundsException();
1145        }
1146        if (meshWidth == 0 || meshHeight == 0) {
1147            return;
1148        }
1149        int count = (meshWidth + 1) * (meshHeight + 1);
1150        // we mul by 2 since we need two floats per vertex
1151        checkRange(verts.length, vertOffset, count * 2);
1152        if (colors != null) {
1153            // no mul by 2, since we need only 1 color per vertex
1154            checkRange(colors.length, colorOffset, count);
1155        }
1156        nativeDrawBitmapMesh(mNativeCanvas, bitmap.ni(), meshWidth, meshHeight,
1157                             verts, vertOffset, colors, colorOffset,
1158                             paint != null ? paint.mNativePaint : 0);
1159    }
1160
1161    public enum VertexMode {
1162        TRIANGLES(0),
1163        TRIANGLE_STRIP(1),
1164        TRIANGLE_FAN(2);
1165
1166        VertexMode(int nativeInt) {
1167            this.nativeInt = nativeInt;
1168        }
1169        final int nativeInt;
1170    }
1171
1172    /**
1173     * Draw the array of vertices, interpreted as triangles (based on mode). The
1174     * verts array is required, and specifies the x,y pairs for each vertex. If
1175     * texs is non-null, then it is used to specify the coordinate in shader
1176     * coordinates to use at each vertex (the paint must have a shader in this
1177     * case). If there is no texs array, but there is a color array, then each
1178     * color is interpolated across its corresponding triangle in a gradient. If
1179     * both texs and colors arrays are present, then they behave as before, but
1180     * the resulting color at each pixels is the result of multiplying the
1181     * colors from the shader and the color-gradient together. The indices array
1182     * is optional, but if it is present, then it is used to specify the index
1183     * of each triangle, rather than just walking through the arrays in order.
1184     *
1185     * @param mode How to interpret the array of vertices
1186     * @param vertexCount The number of values in the vertices array (and
1187     *      corresponding texs and colors arrays if non-null). Each logical
1188     *      vertex is two values (x, y), vertexCount must be a multiple of 2.
1189     * @param verts Array of vertices for the mesh
1190     * @param vertOffset Number of values in the verts to skip before drawing.
1191     * @param texs May be null. If not null, specifies the coordinates to sample
1192     *      into the current shader (e.g. bitmap tile or gradient)
1193     * @param texOffset Number of values in texs to skip before drawing.
1194     * @param colors May be null. If not null, specifies a color for each
1195     *      vertex, to be interpolated across the triangle.
1196     * @param colorOffset Number of values in colors to skip before drawing.
1197     * @param indices If not null, array of indices to reference into the
1198     *      vertex (texs, colors) array.
1199     * @param indexCount number of entries in the indices array (if not null).
1200     * @param paint Specifies the shader to use if the texs array is non-null.
1201     */
1202    public void drawVertices(VertexMode mode, int vertexCount,
1203                             float[] verts, int vertOffset,
1204                             float[] texs, int texOffset,
1205                             int[] colors, int colorOffset,
1206                             short[] indices, int indexOffset,
1207                             int indexCount, Paint paint) {
1208        checkRange(verts.length, vertOffset, vertexCount);
1209        if (texs != null) {
1210            checkRange(texs.length, texOffset, vertexCount);
1211        }
1212        if (colors != null) {
1213            checkRange(colors.length, colorOffset, vertexCount);
1214        }
1215        if (indices != null) {
1216            checkRange(indices.length, indexOffset, indexCount);
1217        }
1218        nativeDrawVertices(mNativeCanvas, mode.nativeInt, vertexCount, verts,
1219                           vertOffset, texs, texOffset, colors, colorOffset,
1220                          indices, indexOffset, indexCount, paint.mNativePaint);
1221    }
1222
1223    /**
1224     * Draw the text, with origin at (x,y), using the specified paint. The
1225     * origin is interpreted based on the Align setting in the paint.
1226     *
1227     * @param text  The text to be drawn
1228     * @param x     The x-coordinate of the origin of the text being drawn
1229     * @param y     The y-coordinate of the origin of the text being drawn
1230     * @param paint The paint used for the text (e.g. color, size, style)
1231     */
1232    public void drawText(char[] text, int index, int count, float x, float y,
1233                         Paint paint) {
1234        if ((index | count | (index + count) |
1235            (text.length - index - count)) < 0) {
1236            throw new IndexOutOfBoundsException();
1237        }
1238        native_drawText(mNativeCanvas, text, index, count, x, y,
1239                        paint.mNativePaint);
1240    }
1241
1242    /**
1243     * Draw the text, with origin at (x,y), using the specified paint. The
1244     * origin is interpreted based on the Align setting in the paint.
1245     *
1246     * @param text  The text to be drawn
1247     * @param x     The x-coordinate of the origin of the text being drawn
1248     * @param y     The y-coordinate of the origin of the text being drawn
1249     * @param paint The paint used for the text (e.g. color, size, style)
1250     */
1251    public native void drawText(String text, float x, float y, Paint paint);
1252
1253    /**
1254     * Draw the text, with origin at (x,y), using the specified paint.
1255     * The origin is interpreted based on the Align setting in the paint.
1256     *
1257     * @param text  The text to be drawn
1258     * @param start The index of the first character in text to draw
1259     * @param end   (end - 1) is the index of the last character in text to draw
1260     * @param x     The x-coordinate of the origin of the text being drawn
1261     * @param y     The y-coordinate of the origin of the text being drawn
1262     * @param paint The paint used for the text (e.g. color, size, style)
1263     */
1264    public void drawText(String text, int start, int end, float x, float y,
1265                         Paint paint) {
1266        if ((start | end | (end - start) | (text.length() - end)) < 0) {
1267            throw new IndexOutOfBoundsException();
1268        }
1269        native_drawText(mNativeCanvas, text, start, end, x, y,
1270                        paint.mNativePaint);
1271    }
1272
1273    /**
1274     * Draw the specified range of text, specified by start/end, with its
1275     * origin at (x,y), in the specified Paint. The origin is interpreted
1276     * based on the Align setting in the Paint.
1277     *
1278     * @param text     The text to be drawn
1279     * @param start    The index of the first character in text to draw
1280     * @param end      (end - 1) is the index of the last character in text
1281     *                 to draw
1282     * @param x        The x-coordinate of origin for where to draw the text
1283     * @param y        The y-coordinate of origin for where to draw the text
1284     * @param paint The paint used for the text (e.g. color, size, style)
1285     */
1286    public void drawText(CharSequence text, int start, int end, float x,
1287                         float y, Paint paint) {
1288        if (text instanceof String || text instanceof SpannedString ||
1289            text instanceof SpannableString) {
1290            native_drawText(mNativeCanvas, text.toString(), start, end, x, y,
1291                            paint.mNativePaint);
1292        }
1293        else if (text instanceof GraphicsOperations) {
1294            ((GraphicsOperations) text).drawText(this, start, end, x, y,
1295                                                     paint);
1296        }
1297        else {
1298            char[] buf = TemporaryBuffer.obtain(end - start);
1299            TextUtils.getChars(text, start, end, buf, 0);
1300            drawText(buf, 0, end - start, x, y, paint);
1301            TemporaryBuffer.recycle(buf);
1302        }
1303    }
1304
1305    /**
1306     * Draw the text in the array, with each character's origin specified by
1307     * the pos array.
1308     *
1309     * @param text     The text to be drawn
1310     * @param index    The index of the first character to draw
1311     * @param count    The number of characters to draw, starting from index.
1312     * @param pos      Array of [x,y] positions, used to position each
1313     *                 character
1314     * @param paint    The paint used for the text (e.g. color, size, style)
1315     */
1316    public void drawPosText(char[] text, int index, int count, float[] pos,
1317                            Paint paint) {
1318        if (index < 0 || index + count > text.length || count*2 > pos.length) {
1319            throw new IndexOutOfBoundsException();
1320        }
1321        native_drawPosText(mNativeCanvas, text, index, count, pos,
1322                           paint.mNativePaint);
1323    }
1324
1325    /**
1326     * Draw the text in the array, with each character's origin specified by
1327     * the pos array.
1328     *
1329     * @param text  The text to be drawn
1330     * @param pos   Array of [x,y] positions, used to position each character
1331     * @param paint The paint used for the text (e.g. color, size, style)
1332     */
1333    public void drawPosText(String text, float[] pos, Paint paint) {
1334        if (text.length()*2 > pos.length) {
1335            throw new ArrayIndexOutOfBoundsException();
1336        }
1337        native_drawPosText(mNativeCanvas, text, pos, paint.mNativePaint);
1338    }
1339
1340    /**
1341     * Draw the text, with origin at (x,y), using the specified paint, along
1342     * the specified path. The paint's Align setting determins where along the
1343     * path to start the text.
1344     *
1345     * @param text     The text to be drawn
1346     * @param path     The path the text should follow for its baseline
1347     * @param hOffset  The distance along the path to add to the text's
1348     *                 starting position
1349     * @param vOffset  The distance above(-) or below(+) the path to position
1350     *                 the text
1351     * @param paint    The paint used for the text (e.g. color, size, style)
1352     */
1353    public void drawTextOnPath(char[] text, int index, int count, Path path,
1354                               float hOffset, float vOffset, Paint paint) {
1355        if (index < 0 || index + count > text.length) {
1356            throw new ArrayIndexOutOfBoundsException();
1357        }
1358        native_drawTextOnPath(mNativeCanvas, text, index, count,
1359                              path.ni(), hOffset, vOffset,
1360                              paint.mNativePaint);
1361    }
1362
1363    /**
1364     * Draw the text, with origin at (x,y), using the specified paint, along
1365     * the specified path. The paint's Align setting determins where along the
1366     * path to start the text.
1367     *
1368     * @param text     The text to be drawn
1369     * @param path     The path the text should follow for its baseline
1370     * @param hOffset  The distance along the path to add to the text's
1371     *                 starting position
1372     * @param vOffset  The distance above(-) or below(+) the path to position
1373     *                 the text
1374     * @param paint    The paint used for the text (e.g. color, size, style)
1375     */
1376    public void drawTextOnPath(String text, Path path, float hOffset,
1377                               float vOffset, Paint paint) {
1378        if (text.length() > 0) {
1379            native_drawTextOnPath(mNativeCanvas, text, path.ni(),
1380                                  hOffset, vOffset, paint.mNativePaint);
1381        }
1382    }
1383
1384    /**
1385     * Save the canvas state, draw the picture, and restore the canvas state.
1386     * This differs from picture.draw(canvas), which does not perform any
1387     * save/restore.
1388     *
1389     * @param picture  The picture to be drawn
1390     */
1391    public void drawPicture(Picture picture) {
1392        picture.endRecording();
1393        native_drawPicture(mNativeCanvas, picture.ni());
1394    }
1395
1396    /**
1397     * Draw the picture, stretched to fit into the dst rectangle.
1398     */
1399    public void drawPicture(Picture picture, RectF dst) {
1400        save();
1401        translate(dst.left, dst.top);
1402        if (picture.getWidth() > 0 && picture.getHeight() > 0) {
1403            scale(dst.width() / picture.getWidth(),
1404                  dst.height() / picture.getHeight());
1405        }
1406        drawPicture(picture);
1407        restore();
1408    }
1409
1410    /**
1411     * Draw the picture, stretched to fit into the dst rectangle.
1412     */
1413    public void drawPicture(Picture picture, Rect dst) {
1414        save();
1415        translate(dst.left, dst.top);
1416        if (picture.getWidth() > 0 && picture.getHeight() > 0) {
1417            scale((float)dst.width() / picture.getWidth(),
1418                  (float)dst.height() / picture.getHeight());
1419        }
1420        drawPicture(picture);
1421        restore();
1422    }
1423
1424    protected void finalize() throws Throwable {
1425        super.finalize();
1426        // If the constructor threw an exception before setting mNativeCanvas, the native finalizer
1427        // must not be invoked.
1428        if (mNativeCanvas != 0) {
1429            finalizer(mNativeCanvas);
1430        }
1431    }
1432
1433    /**
1434     * Free up as much memory as possible from private caches (e.g. fonts,
1435     * images)
1436     *
1437     * @hide - for now
1438     */
1439    public static native void freeCaches();
1440
1441    private static native int initRaster(int nativeBitmapOrZero);
1442    private static native int initGL();
1443    private static native void native_setBitmap(int nativeCanvas, int bitmap);
1444    private static native void nativeSetViewport(int nCanvas, int w, int h);
1445    private static native int native_saveLayer(int nativeCanvas, RectF bounds,
1446                                               int paint, int layerFlags);
1447    private static native int native_saveLayer(int nativeCanvas, float l,
1448                                               float t, float r, float b,
1449                                               int paint, int layerFlags);
1450    private static native int native_saveLayerAlpha(int nativeCanvas,
1451                                                    RectF bounds, int alpha,
1452                                                    int layerFlags);
1453    private static native int native_saveLayerAlpha(int nativeCanvas, float l,
1454                                                    float t, float r, float b,
1455                                                    int alpha, int layerFlags);
1456
1457    private static native void native_concat(int nCanvas, int nMatrix);
1458    private static native void native_setMatrix(int nCanvas, int nMatrix);
1459    private static native boolean native_clipRect(int nCanvas,
1460                                                  float left, float top,
1461                                                  float right, float bottom,
1462                                                  int regionOp);
1463    private static native boolean native_clipPath(int nativeCanvas,
1464                                                  int nativePath,
1465                                                  int regionOp);
1466    private static native boolean native_clipRegion(int nativeCanvas,
1467                                                    int nativeRegion,
1468                                                    int regionOp);
1469    private static native void nativeSetDrawFilter(int nativeCanvas,
1470                                                   int nativeFilter);
1471    private static native boolean native_getClipBounds(int nativeCanvas,
1472                                                       Rect bounds);
1473    private static native void native_getCTM(int canvas, int matrix);
1474    private static native boolean native_quickReject(int nativeCanvas,
1475                                                     RectF rect,
1476                                                     int native_edgeType);
1477    private static native boolean native_quickReject(int nativeCanvas,
1478                                                     int path,
1479                                                     int native_edgeType);
1480    private static native boolean native_quickReject(int nativeCanvas,
1481                                                     float left, float top,
1482                                                     float right, float bottom,
1483                                                     int native_edgeType);
1484    private static native void native_drawRGB(int nativeCanvas, int r, int g,
1485                                              int b);
1486    private static native void native_drawARGB(int nativeCanvas, int a, int r,
1487                                               int g, int b);
1488    private static native void native_drawColor(int nativeCanvas, int color);
1489    private static native void native_drawColor(int nativeCanvas, int color,
1490                                                int mode);
1491    private static native void native_drawPaint(int nativeCanvas, int paint);
1492    private static native void native_drawLine(int nativeCanvas, float startX,
1493                                               float startY, float stopX,
1494                                               float stopY, int paint);
1495    private static native void native_drawRect(int nativeCanvas, RectF rect,
1496                                               int paint);
1497    private static native void native_drawRect(int nativeCanvas, float left,
1498                                               float top, float right,
1499                                               float bottom, int paint);
1500    private static native void native_drawOval(int nativeCanvas, RectF oval,
1501                                               int paint);
1502    private static native void native_drawCircle(int nativeCanvas, float cx,
1503                                                 float cy, float radius,
1504                                                 int paint);
1505    private static native void native_drawArc(int nativeCanvas, RectF oval,
1506                                              float startAngle, float sweep,
1507                                              boolean useCenter, int paint);
1508    private static native void native_drawRoundRect(int nativeCanvas,
1509                                                    RectF rect, float rx,
1510                                                    float ry, int paint);
1511    private static native void native_drawPath(int nativeCanvas, int path,
1512                                               int paint);
1513    private native void native_drawBitmap(int nativeCanvas, int bitmap,
1514                                                 float left, float top,
1515                                                 int nativePaintOrZero,
1516                                                 int canvasDensity, int bitmapDensity);
1517    private native void native_drawBitmap(int nativeCanvas, int bitmap,
1518                                                 Rect src, RectF dst,
1519                                                 int nativePaintOrZero);
1520    private static native void native_drawBitmap(int nativeCanvas, int bitmap,
1521                                                 Rect src, Rect dst,
1522                                                 int nativePaintOrZero);
1523    private static native void native_drawBitmap(int nativeCanvas, int[] colors,
1524                                                int offset, int stride, float x,
1525                                                 float y, int width, int height,
1526                                                 boolean hasAlpha,
1527                                                 int nativePaintOrZero);
1528    private static native void nativeDrawBitmapMatrix(int nCanvas, int nBitmap,
1529                                                      int nMatrix, int nPaint);
1530    private static native void nativeDrawBitmapMesh(int nCanvas, int nBitmap,
1531                                                    int meshWidth, int meshHeight,
1532                                                    float[] verts, int vertOffset,
1533                                                    int[] colors, int colorOffset, int nPaint);
1534    private static native void nativeDrawVertices(int nCanvas, int mode, int n,
1535                   float[] verts, int vertOffset, float[] texs, int texOffset,
1536                   int[] colors, int colorOffset, short[] indices,
1537                   int indexOffset, int indexCount, int nPaint);
1538
1539    private static native void native_drawText(int nativeCanvas, char[] text,
1540                                               int index, int count, float x,
1541                                               float y, int paint);
1542    private static native void native_drawText(int nativeCanvas, String text,
1543                                               int start, int end, float x,
1544                                               float y, int paint);
1545    private static native void native_drawPosText(int nativeCanvas,
1546                                                  char[] text, int index,
1547                                                  int count, float[] pos,
1548                                                  int paint);
1549    private static native void native_drawPosText(int nativeCanvas,
1550                                                  String text, float[] pos,
1551                                                  int paint);
1552    private static native void native_drawTextOnPath(int nativeCanvas,
1553                                                     char[] text, int index,
1554                                                     int count, int path,
1555                                                     float hOffset,
1556                                                     float vOffset, int paint);
1557    private static native void native_drawTextOnPath(int nativeCanvas,
1558                                                     String text, int path,
1559                                                     float hOffset,
1560                                                     float vOffset, int paint);
1561    private static native void native_drawPicture(int nativeCanvas,
1562                                                  int nativePicture);
1563    private static native void finalizer(int nativeCanvas);
1564}
1565