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