Canvas.java revision ce0537b80087a6225273040a987414b1dd081aa0
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     * Draw the specified bitmap, with its top/left corner at (x,y), using
1004     * the specified paint, transformed by the current matrix.
1005     *
1006     * <p>Note: if the paint contains a maskfilter that generates a mask which
1007     * extends beyond the bitmap's original width/height (e.g. BlurMaskFilter),
1008     * then the bitmap will be drawn as if it were in a Shader with CLAMP mode.
1009     * Thus the color outside of the original width/height will be the edge
1010     * color replicated.
1011     *
1012     * <p>If the bitmap and canvas have different densities, this function
1013     * will take care of automatically scaling the bitmap to draw at the
1014     * same density as the canvas.
1015     *
1016     * @param bitmap The bitmap to be drawn
1017     * @param left   The position of the left side of the bitmap being drawn
1018     * @param top    The position of the top side of the bitmap being drawn
1019     * @param paint  The paint used to draw the bitmap (may be null)
1020     */
1021    public void drawBitmap(Bitmap bitmap, float left, float top, Paint paint) {
1022        throwIfRecycled(bitmap);
1023        native_drawBitmap(mNativeCanvas, bitmap.ni(), left, top,
1024                paint != null ? paint.mNativePaint : 0, mDensity, mScreenDensity,
1025                bitmap.mDensity);
1026    }
1027
1028    /**
1029     * Draw the specified bitmap, scaling/translating automatically to fill
1030     * the destination rectangle. If the source rectangle is not null, it
1031     * specifies the subset of the bitmap to draw.
1032     *
1033     * <p>Note: if the paint contains a maskfilter that generates a mask which
1034     * extends beyond the bitmap's original width/height (e.g. BlurMaskFilter),
1035     * then the bitmap will be drawn as if it were in a Shader with CLAMP mode.
1036     * Thus the color outside of the original width/height will be the edge
1037     * color replicated.
1038     *
1039     * <p>This function <em>ignores the density associated with the bitmap</em>.
1040     * This is because the source and destination rectangle coordinate
1041     * spaces are in their respective densities, so must already have the
1042     * appropriate scaling factor applied.
1043     *
1044     * @param bitmap The bitmap to be drawn
1045     * @param src    May be null. The subset of the bitmap to be drawn
1046     * @param dst    The rectangle that the bitmap will be scaled/translated
1047     *               to fit into
1048     * @param paint  May be null. The paint used to draw the bitmap
1049     */
1050    public void drawBitmap(Bitmap bitmap, Rect src, RectF dst, Paint paint) {
1051        if (dst == null) {
1052            throw new NullPointerException();
1053        }
1054        throwIfRecycled(bitmap);
1055        native_drawBitmap(mNativeCanvas, bitmap.ni(), src, dst,
1056                          paint != null ? paint.mNativePaint : 0,
1057                          mScreenDensity, bitmap.mDensity);
1058    }
1059
1060    /**
1061     * Draw the specified bitmap, scaling/translating automatically to fill
1062     * the destination rectangle. If the source rectangle is not null, it
1063     * specifies the subset of the bitmap to draw.
1064     *
1065     * <p>Note: if the paint contains a maskfilter that generates a mask which
1066     * extends beyond the bitmap's original width/height (e.g. BlurMaskFilter),
1067     * then the bitmap will be drawn as if it were in a Shader with CLAMP mode.
1068     * Thus the color outside of the original width/height will be the edge
1069     * color replicated.
1070     *
1071     * <p>This function <em>ignores the density associated with the bitmap</em>.
1072     * This is because the source and destination rectangle coordinate
1073     * spaces are in their respective densities, so must already have the
1074     * appropriate scaling factor applied.
1075     *
1076     * @param bitmap The bitmap to be drawn
1077     * @param src    May be null. The subset of the bitmap to be drawn
1078     * @param dst    The rectangle that the bitmap will be scaled/translated
1079     *               to fit into
1080     * @param paint  May be null. The paint used to draw the bitmap
1081     */
1082    public void drawBitmap(Bitmap bitmap, Rect src, Rect dst, Paint paint) {
1083        if (dst == null) {
1084            throw new NullPointerException();
1085        }
1086        throwIfRecycled(bitmap);
1087        native_drawBitmap(mNativeCanvas, bitmap.ni(), src, dst,
1088                          paint != null ? paint.mNativePaint : 0,
1089                          mScreenDensity, bitmap.mDensity);
1090    }
1091
1092    /**
1093     * Treat the specified array of colors as a bitmap, and draw it. This gives
1094     * the same result as first creating a bitmap from the array, and then
1095     * drawing it, but this method avoids explicitly creating a bitmap object
1096     * which can be more efficient if the colors are changing often.
1097     *
1098     * @param colors Array of colors representing the pixels of the bitmap
1099     * @param offset Offset into the array of colors for the first pixel
1100     * @param stride The number of of colors in the array between rows (must be
1101     *               >= width or <= -width).
1102     * @param x The X coordinate for where to draw the bitmap
1103     * @param y The Y coordinate for where to draw the bitmap
1104     * @param width The width of the bitmap
1105     * @param height The height of the bitmap
1106     * @param hasAlpha True if the alpha channel of the colors contains valid
1107     *                 values. If false, the alpha byte is ignored (assumed to
1108     *                 be 0xFF for every pixel).
1109     * @param paint  May be null. The paint used to draw the bitmap
1110     */
1111    public void drawBitmap(int[] colors, int offset, int stride, float x,
1112                           float y, int width, int height, boolean hasAlpha,
1113                           Paint paint) {
1114        // check for valid input
1115        if (width < 0) {
1116            throw new IllegalArgumentException("width must be >= 0");
1117        }
1118        if (height < 0) {
1119            throw new IllegalArgumentException("height must be >= 0");
1120        }
1121        if (Math.abs(stride) < width) {
1122            throw new IllegalArgumentException("abs(stride) must be >= width");
1123        }
1124        int lastScanline = offset + (height - 1) * stride;
1125        int length = colors.length;
1126        if (offset < 0 || (offset + width > length) || lastScanline < 0
1127                || (lastScanline + width > length)) {
1128            throw new ArrayIndexOutOfBoundsException();
1129        }
1130        // quick escape if there's nothing to draw
1131        if (width == 0 || height == 0) {
1132            return;
1133        }
1134        // punch down to native for the actual draw
1135        native_drawBitmap(mNativeCanvas, colors, offset, stride, x, y, width, height, hasAlpha,
1136                paint != null ? paint.mNativePaint : 0);
1137    }
1138
1139    /** Legacy version of drawBitmap(int[] colors, ...) that took ints for x,y
1140     */
1141    public void drawBitmap(int[] colors, int offset, int stride, int x, int y,
1142                           int width, int height, boolean hasAlpha,
1143                           Paint paint) {
1144        // call through to the common float version
1145        drawBitmap(colors, offset, stride, (float)x, (float)y, width, height,
1146                   hasAlpha, paint);
1147    }
1148
1149    /**
1150     * Draw the bitmap using the specified matrix.
1151     *
1152     * @param bitmap The bitmap to draw
1153     * @param matrix The matrix used to transform the bitmap when it is drawn
1154     * @param paint  May be null. The paint used to draw the bitmap
1155     */
1156    public void drawBitmap(Bitmap bitmap, Matrix matrix, Paint paint) {
1157        nativeDrawBitmapMatrix(mNativeCanvas, bitmap.ni(), matrix.ni(),
1158                paint != null ? paint.mNativePaint : 0);
1159    }
1160
1161    private static void checkRange(int length, int offset, int count) {
1162        if ((offset | count) < 0 || offset + count > length) {
1163            throw new ArrayIndexOutOfBoundsException();
1164        }
1165    }
1166
1167    /**
1168     * Draw the bitmap through the mesh, where mesh vertices are evenly
1169     * distributed across the bitmap. There are meshWidth+1 vertices across, and
1170     * meshHeight+1 vertices down. The verts array is accessed in row-major
1171     * order, so that the first meshWidth+1 vertices are distributed across the
1172     * top of the bitmap from left to right. A more general version of this
1173     * methid is drawVertices().
1174     *
1175     * @param bitmap The bitmap to draw using the mesh
1176     * @param meshWidth The number of columns in the mesh. Nothing is drawn if
1177     *                  this is 0
1178     * @param meshHeight The number of rows in the mesh. Nothing is drawn if
1179     *                   this is 0
1180     * @param verts Array of x,y pairs, specifying where the mesh should be
1181     *              drawn. There must be at least
1182     *              (meshWidth+1) * (meshHeight+1) * 2 + meshOffset values
1183     *              in the array
1184     * @param vertOffset Number of verts elements to skip before drawing
1185     * @param colors May be null. Specifies a color at each vertex, which is
1186     *               interpolated across the cell, and whose values are
1187     *               multiplied by the corresponding bitmap colors. If not null,
1188     *               there must be at least (meshWidth+1) * (meshHeight+1) +
1189     *               colorOffset values in the array.
1190     * @param colorOffset Number of color elements to skip before drawing
1191     * @param paint  May be null. The paint used to draw the bitmap
1192     */
1193    public void drawBitmapMesh(Bitmap bitmap, int meshWidth, int meshHeight,
1194                               float[] verts, int vertOffset,
1195                               int[] colors, int colorOffset, Paint paint) {
1196        if ((meshWidth | meshHeight | vertOffset | colorOffset) < 0) {
1197            throw new ArrayIndexOutOfBoundsException();
1198        }
1199        if (meshWidth == 0 || meshHeight == 0) {
1200            return;
1201        }
1202        int count = (meshWidth + 1) * (meshHeight + 1);
1203        // we mul by 2 since we need two floats per vertex
1204        checkRange(verts.length, vertOffset, count * 2);
1205        if (colors != null) {
1206            // no mul by 2, since we need only 1 color per vertex
1207            checkRange(colors.length, colorOffset, count);
1208        }
1209        nativeDrawBitmapMesh(mNativeCanvas, bitmap.ni(), meshWidth, meshHeight,
1210                             verts, vertOffset, colors, colorOffset,
1211                             paint != null ? paint.mNativePaint : 0);
1212    }
1213
1214    public enum VertexMode {
1215        TRIANGLES(0),
1216        TRIANGLE_STRIP(1),
1217        TRIANGLE_FAN(2);
1218
1219        VertexMode(int nativeInt) {
1220            this.nativeInt = nativeInt;
1221        }
1222        final int nativeInt;
1223    }
1224
1225    /**
1226     * Draw the array of vertices, interpreted as triangles (based on mode). The
1227     * verts array is required, and specifies the x,y pairs for each vertex. If
1228     * texs is non-null, then it is used to specify the coordinate in shader
1229     * coordinates to use at each vertex (the paint must have a shader in this
1230     * case). If there is no texs array, but there is a color array, then each
1231     * color is interpolated across its corresponding triangle in a gradient. If
1232     * both texs and colors arrays are present, then they behave as before, but
1233     * the resulting color at each pixels is the result of multiplying the
1234     * colors from the shader and the color-gradient together. The indices array
1235     * is optional, but if it is present, then it is used to specify the index
1236     * of each triangle, rather than just walking through the arrays in order.
1237     *
1238     * @param mode How to interpret the array of vertices
1239     * @param vertexCount The number of values in the vertices array (and
1240     *      corresponding texs and colors arrays if non-null). Each logical
1241     *      vertex is two values (x, y), vertexCount must be a multiple of 2.
1242     * @param verts Array of vertices for the mesh
1243     * @param vertOffset Number of values in the verts to skip before drawing.
1244     * @param texs May be null. If not null, specifies the coordinates to sample
1245     *      into the current shader (e.g. bitmap tile or gradient)
1246     * @param texOffset Number of values in texs to skip before drawing.
1247     * @param colors May be null. If not null, specifies a color for each
1248     *      vertex, to be interpolated across the triangle.
1249     * @param colorOffset Number of values in colors to skip before drawing.
1250     * @param indices If not null, array of indices to reference into the
1251     *      vertex (texs, colors) array.
1252     * @param indexCount number of entries in the indices array (if not null).
1253     * @param paint Specifies the shader to use if the texs array is non-null.
1254     */
1255    public void drawVertices(VertexMode mode, int vertexCount,
1256                             float[] verts, int vertOffset,
1257                             float[] texs, int texOffset,
1258                             int[] colors, int colorOffset,
1259                             short[] indices, int indexOffset,
1260                             int indexCount, Paint paint) {
1261        checkRange(verts.length, vertOffset, vertexCount);
1262        if (texs != null) {
1263            checkRange(texs.length, texOffset, vertexCount);
1264        }
1265        if (colors != null) {
1266            checkRange(colors.length, colorOffset, vertexCount / 2);
1267        }
1268        if (indices != null) {
1269            checkRange(indices.length, indexOffset, indexCount);
1270        }
1271        nativeDrawVertices(mNativeCanvas, mode.nativeInt, vertexCount, verts,
1272                           vertOffset, texs, texOffset, colors, colorOffset,
1273                          indices, indexOffset, indexCount, paint.mNativePaint);
1274    }
1275
1276    /**
1277     * Draw the text, with origin at (x,y), using the specified paint. The
1278     * origin is interpreted based on the Align setting in the paint.
1279     *
1280     * @param text  The text to be drawn
1281     * @param x     The x-coordinate of the origin of the text being drawn
1282     * @param y     The y-coordinate of the origin of the text being drawn
1283     * @param paint The paint used for the text (e.g. color, size, style)
1284     */
1285    public void drawText(char[] text, int index, int count, float x, float y,
1286                         Paint paint) {
1287        if ((index | count | (index + count) |
1288            (text.length - index - count)) < 0) {
1289            throw new IndexOutOfBoundsException();
1290        }
1291        native_drawText(mNativeCanvas, text, index, count, x, y, paint.mBidiFlags,
1292                paint.mNativePaint);
1293    }
1294
1295    /**
1296     * Draw the text, with origin at (x,y), using the specified paint. The
1297     * origin is interpreted based on the Align setting in the paint.
1298     *
1299     * @param text  The text to be drawn
1300     * @param x     The x-coordinate of the origin of the text being drawn
1301     * @param y     The y-coordinate of the origin of the text being drawn
1302     * @param paint The paint used for the text (e.g. color, size, style)
1303     */
1304    public void drawText(String text, float x, float y, Paint paint) {
1305        native_drawText(mNativeCanvas, text, 0, text.length(), x, y, paint.mBidiFlags,
1306                paint.mNativePaint);
1307    }
1308
1309    /**
1310     * Draw the text, with origin at (x,y), using the specified paint.
1311     * The origin is interpreted based on the Align setting in the paint.
1312     *
1313     * @param text  The text to be drawn
1314     * @param start The index of the first character in text to draw
1315     * @param end   (end - 1) is the index of the last character in text to draw
1316     * @param x     The x-coordinate of the origin of the text being drawn
1317     * @param y     The y-coordinate of the origin of the text being drawn
1318     * @param paint The paint used for the text (e.g. color, size, style)
1319     */
1320    public void drawText(String text, int start, int end, float x, float y,
1321                         Paint paint) {
1322        if ((start | end | (end - start) | (text.length() - end)) < 0) {
1323            throw new IndexOutOfBoundsException();
1324        }
1325        native_drawText(mNativeCanvas, text, start, end, x, y, paint.mBidiFlags,
1326                paint.mNativePaint);
1327    }
1328
1329    /**
1330     * Draw the specified range of text, specified by start/end, with its
1331     * origin at (x,y), in the specified Paint. The origin is interpreted
1332     * based on the Align setting in the Paint.
1333     *
1334     * @param text     The text to be drawn
1335     * @param start    The index of the first character in text to draw
1336     * @param end      (end - 1) is the index of the last character in text
1337     *                 to draw
1338     * @param x        The x-coordinate of origin for where to draw the text
1339     * @param y        The y-coordinate of origin for where to draw the text
1340     * @param paint The paint used for the text (e.g. color, size, style)
1341     */
1342    public void drawText(CharSequence text, int start, int end, float x,
1343                         float y, Paint paint) {
1344        if (text instanceof String || text instanceof SpannedString ||
1345            text instanceof SpannableString) {
1346            native_drawText(mNativeCanvas, text.toString(), start, end, x, y,
1347                            paint.mBidiFlags, paint.mNativePaint);
1348        } else if (text instanceof GraphicsOperations) {
1349            ((GraphicsOperations) text).drawText(this, start, end, x, y,
1350                                                     paint);
1351        } else {
1352            char[] buf = TemporaryBuffer.obtain(end - start);
1353            TextUtils.getChars(text, start, end, buf, 0);
1354            native_drawText(mNativeCanvas, buf, 0, end - start, x, y,
1355                    paint.mBidiFlags, paint.mNativePaint);
1356            TemporaryBuffer.recycle(buf);
1357        }
1358    }
1359
1360    /**
1361     * Render a run of all LTR or all RTL text, with shaping. This does not run
1362     * bidi on the provided text, but renders it as a uniform right-to-left or
1363     * left-to-right run, as indicated by dir. Alignment of the text is as
1364     * determined by the Paint's TextAlign value.
1365     *
1366     * @param text the text to render
1367     * @param index the start of the text to render
1368     * @param count the count of chars to render
1369     * @param contextIndex the start of the context for shaping.  Must be
1370     *         no greater than index.
1371     * @param contextCount the number of characters in the context for shaping.
1372     *         ContexIndex + contextCount must be no less than index
1373     *         + count.
1374     * @param x the x position at which to draw the text
1375     * @param y the y position at which to draw the text
1376     * @param dir the run direction, either {@link #DIRECTION_LTR} or
1377     *         {@link #DIRECTION_RTL}.
1378     * @param paint the paint
1379     * @hide
1380     */
1381    public void drawTextRun(char[] text, int index, int count,
1382            int contextIndex, int contextCount, float x, float y, int dir,
1383            Paint paint) {
1384
1385        if (text == null) {
1386            throw new NullPointerException("text is null");
1387        }
1388        if (paint == null) {
1389            throw new NullPointerException("paint is null");
1390        }
1391        if ((index | count | text.length - index - count) < 0) {
1392            throw new IndexOutOfBoundsException();
1393        }
1394        if (dir != DIRECTION_LTR && dir != DIRECTION_RTL) {
1395            throw new IllegalArgumentException("unknown dir: " + dir);
1396        }
1397
1398        native_drawTextRun(mNativeCanvas, text, index, count,
1399                contextIndex, contextCount, x, y, dir, paint.mNativePaint);
1400    }
1401
1402    /**
1403     * Render a run of all LTR or all RTL text, with shaping. This does not run
1404     * bidi on the provided text, but renders it as a uniform right-to-left or
1405     * left-to-right run, as indicated by dir. Alignment of the text is as
1406     * determined by the Paint's TextAlign value.
1407     *
1408     * @param text the text to render
1409     * @param start the start of the text to render. Data before this position
1410     *            can be used for shaping context.
1411     * @param end the end of the text to render. Data at or after this
1412     *            position can be used for shaping context.
1413     * @param x the x position at which to draw the text
1414     * @param y the y position at which to draw the text
1415     * @param dir the run direction, either 0 for LTR or 1 for RTL.
1416     * @param paint the paint
1417     * @hide
1418     */
1419    public void drawTextRun(CharSequence text, int start, int end,
1420            int contextStart, int contextEnd, float x, float y, int dir,
1421            Paint paint) {
1422
1423        if (text == null) {
1424            throw new NullPointerException("text is null");
1425        }
1426        if (paint == null) {
1427            throw new NullPointerException("paint is null");
1428        }
1429        if ((start | end | end - start | text.length() - end) < 0) {
1430            throw new IndexOutOfBoundsException();
1431        }
1432
1433        int flags = dir == 0 ? 0 : 1;
1434
1435        if (text instanceof String || text instanceof SpannedString ||
1436                text instanceof SpannableString) {
1437            native_drawTextRun(mNativeCanvas, text.toString(), start, end,
1438                    contextStart, contextEnd, x, y, flags, paint.mNativePaint);
1439        } else if (text instanceof GraphicsOperations) {
1440            ((GraphicsOperations) text).drawTextRun(this, start, end,
1441                    contextStart, contextEnd, x, y, flags, paint);
1442        } else {
1443            int contextLen = contextEnd - contextStart;
1444            int len = end - start;
1445            char[] buf = TemporaryBuffer.obtain(contextLen);
1446            TextUtils.getChars(text, contextStart, contextEnd, buf, 0);
1447            native_drawTextRun(mNativeCanvas, buf, start - contextStart, len,
1448                    0, contextLen, x, y, flags, paint.mNativePaint);
1449            TemporaryBuffer.recycle(buf);
1450        }
1451    }
1452
1453    /**
1454     * Draw the text in the array, with each character's origin specified by
1455     * the pos array.
1456     *
1457     * @param text     The text to be drawn
1458     * @param index    The index of the first character to draw
1459     * @param count    The number of characters to draw, starting from index.
1460     * @param pos      Array of [x,y] positions, used to position each
1461     *                 character
1462     * @param paint    The paint used for the text (e.g. color, size, style)
1463     */
1464    public void drawPosText(char[] text, int index, int count, float[] pos,
1465                            Paint paint) {
1466        if (index < 0 || index + count > text.length || count*2 > pos.length) {
1467            throw new IndexOutOfBoundsException();
1468        }
1469        native_drawPosText(mNativeCanvas, text, index, count, pos,
1470                           paint.mNativePaint);
1471    }
1472
1473    /**
1474     * Draw the text in the array, with each character's origin specified by
1475     * the pos array.
1476     *
1477     * @param text  The text to be drawn
1478     * @param pos   Array of [x,y] positions, used to position each character
1479     * @param paint The paint used for the text (e.g. color, size, style)
1480     */
1481    public void drawPosText(String text, float[] pos, Paint paint) {
1482        if (text.length()*2 > pos.length) {
1483            throw new ArrayIndexOutOfBoundsException();
1484        }
1485        native_drawPosText(mNativeCanvas, text, pos, paint.mNativePaint);
1486    }
1487
1488    /**
1489     * Draw the text, with origin at (x,y), using the specified paint, along
1490     * the specified path. The paint's Align setting determins where along the
1491     * path to start the text.
1492     *
1493     * @param text     The text to be drawn
1494     * @param path     The path the text should follow for its baseline
1495     * @param hOffset  The distance along the path to add to the text's
1496     *                 starting position
1497     * @param vOffset  The distance above(-) or below(+) the path to position
1498     *                 the text
1499     * @param paint    The paint used for the text (e.g. color, size, style)
1500     */
1501    public void drawTextOnPath(char[] text, int index, int count, Path path,
1502                               float hOffset, float vOffset, Paint paint) {
1503        if (index < 0 || index + count > text.length) {
1504            throw new ArrayIndexOutOfBoundsException();
1505        }
1506        native_drawTextOnPath(mNativeCanvas, text, index, count,
1507                              path.ni(), hOffset, vOffset,
1508                              paint.mNativePaint);
1509    }
1510
1511    /**
1512     * Draw the text, with origin at (x,y), using the specified paint, along
1513     * the specified path. The paint's Align setting determins where along the
1514     * path to start the text.
1515     *
1516     * @param text     The text to be drawn
1517     * @param path     The path the text should follow for its baseline
1518     * @param hOffset  The distance along the path to add to the text's
1519     *                 starting position
1520     * @param vOffset  The distance above(-) or below(+) the path to position
1521     *                 the text
1522     * @param paint    The paint used for the text (e.g. color, size, style)
1523     */
1524    public void drawTextOnPath(String text, Path path, float hOffset,
1525                               float vOffset, Paint paint) {
1526        if (text.length() > 0) {
1527            native_drawTextOnPath(mNativeCanvas, text, path.ni(),
1528                                  hOffset, vOffset, paint.mNativePaint);
1529        }
1530    }
1531
1532    /**
1533     * Save the canvas state, draw the picture, and restore the canvas state.
1534     * This differs from picture.draw(canvas), which does not perform any
1535     * save/restore.
1536     *
1537     * @param picture  The picture to be drawn
1538     */
1539    public void drawPicture(Picture picture) {
1540        picture.endRecording();
1541        native_drawPicture(mNativeCanvas, picture.ni());
1542    }
1543
1544    /**
1545     * Draw the picture, stretched to fit into the dst rectangle.
1546     */
1547    public void drawPicture(Picture picture, RectF dst) {
1548        save();
1549        translate(dst.left, dst.top);
1550        if (picture.getWidth() > 0 && picture.getHeight() > 0) {
1551            scale(dst.width() / picture.getWidth(),
1552                  dst.height() / picture.getHeight());
1553        }
1554        drawPicture(picture);
1555        restore();
1556    }
1557
1558    /**
1559     * Draw the picture, stretched to fit into the dst rectangle.
1560     */
1561    public void drawPicture(Picture picture, Rect dst) {
1562        save();
1563        translate(dst.left, dst.top);
1564        if (picture.getWidth() > 0 && picture.getHeight() > 0) {
1565            scale((float)dst.width() / picture.getWidth(),
1566                  (float)dst.height() / picture.getHeight());
1567        }
1568        drawPicture(picture);
1569        restore();
1570    }
1571
1572    protected void finalize() throws Throwable {
1573        super.finalize();
1574        // If the constructor threw an exception before setting mNativeCanvas, the native finalizer
1575        // must not be invoked.
1576        if (mNativeCanvas != 0) {
1577            finalizer(mNativeCanvas);
1578        }
1579    }
1580
1581    /**
1582     * Free up as much memory as possible from private caches (e.g. fonts,
1583     * images)
1584     *
1585     * @hide - for now
1586     */
1587    public static native void freeCaches();
1588
1589    private static native int initRaster(int nativeBitmapOrZero);
1590    private static native int initGL();
1591    private static native void native_setBitmap(int nativeCanvas, int bitmap);
1592    private static native void nativeSetViewport(int nCanvas, int w, int h);
1593    private static native int native_saveLayer(int nativeCanvas, RectF bounds,
1594                                               int paint, int layerFlags);
1595    private static native int native_saveLayer(int nativeCanvas, float l,
1596                                               float t, float r, float b,
1597                                               int paint, int layerFlags);
1598    private static native int native_saveLayerAlpha(int nativeCanvas,
1599                                                    RectF bounds, int alpha,
1600                                                    int layerFlags);
1601    private static native int native_saveLayerAlpha(int nativeCanvas, float l,
1602                                                    float t, float r, float b,
1603                                                    int alpha, int layerFlags);
1604
1605    private static native void native_concat(int nCanvas, int nMatrix);
1606    private static native void native_setMatrix(int nCanvas, int nMatrix);
1607    private static native boolean native_clipRect(int nCanvas,
1608                                                  float left, float top,
1609                                                  float right, float bottom,
1610                                                  int regionOp);
1611    private static native boolean native_clipPath(int nativeCanvas,
1612                                                  int nativePath,
1613                                                  int regionOp);
1614    private static native boolean native_clipRegion(int nativeCanvas,
1615                                                    int nativeRegion,
1616                                                    int regionOp);
1617    private static native void nativeSetDrawFilter(int nativeCanvas,
1618                                                   int nativeFilter);
1619    private static native boolean native_getClipBounds(int nativeCanvas,
1620                                                       Rect bounds);
1621    private static native void native_getCTM(int canvas, int matrix);
1622    private static native boolean native_quickReject(int nativeCanvas,
1623                                                     RectF rect,
1624                                                     int native_edgeType);
1625    private static native boolean native_quickReject(int nativeCanvas,
1626                                                     int path,
1627                                                     int native_edgeType);
1628    private static native boolean native_quickReject(int nativeCanvas,
1629                                                     float left, float top,
1630                                                     float right, float bottom,
1631                                                     int native_edgeType);
1632    private static native void native_drawRGB(int nativeCanvas, int r, int g,
1633                                              int b);
1634    private static native void native_drawARGB(int nativeCanvas, int a, int r,
1635                                               int g, int b);
1636    private static native void native_drawColor(int nativeCanvas, int color);
1637    private static native void native_drawColor(int nativeCanvas, int color,
1638                                                int mode);
1639    private static native void native_drawPaint(int nativeCanvas, int paint);
1640    private static native void native_drawLine(int nativeCanvas, float startX,
1641                                               float startY, float stopX,
1642                                               float stopY, int paint);
1643    private static native void native_drawRect(int nativeCanvas, RectF rect,
1644                                               int paint);
1645    private static native void native_drawRect(int nativeCanvas, float left,
1646                                               float top, float right,
1647                                               float bottom, int paint);
1648    private static native void native_drawOval(int nativeCanvas, RectF oval,
1649                                               int paint);
1650    private static native void native_drawCircle(int nativeCanvas, float cx,
1651                                                 float cy, float radius,
1652                                                 int paint);
1653    private static native void native_drawArc(int nativeCanvas, RectF oval,
1654                                              float startAngle, float sweep,
1655                                              boolean useCenter, int paint);
1656    private static native void native_drawRoundRect(int nativeCanvas,
1657                                                    RectF rect, float rx,
1658                                                    float ry, int paint);
1659    private static native void native_drawPath(int nativeCanvas, int path,
1660                                               int paint);
1661    private native void native_drawBitmap(int nativeCanvas, int bitmap,
1662                                                 float left, float top,
1663                                                 int nativePaintOrZero,
1664                                                 int canvasDensity,
1665                                                 int screenDensity,
1666                                                 int bitmapDensity);
1667    private native void native_drawBitmap(int nativeCanvas, int bitmap,
1668                                                 Rect src, RectF dst,
1669                                                 int nativePaintOrZero,
1670                                                 int screenDensity,
1671                                                 int bitmapDensity);
1672    private static native void native_drawBitmap(int nativeCanvas, int bitmap,
1673                                                 Rect src, Rect dst,
1674                                                 int nativePaintOrZero,
1675                                                 int screenDensity,
1676                                                 int bitmapDensity);
1677    private static native void native_drawBitmap(int nativeCanvas, int[] colors,
1678                                                int offset, int stride, float x,
1679                                                 float y, int width, int height,
1680                                                 boolean hasAlpha,
1681                                                 int nativePaintOrZero);
1682    private static native void nativeDrawBitmapMatrix(int nCanvas, int nBitmap,
1683                                                      int nMatrix, int nPaint);
1684    private static native void nativeDrawBitmapMesh(int nCanvas, int nBitmap,
1685                                                    int meshWidth, int meshHeight,
1686                                                    float[] verts, int vertOffset,
1687                                                    int[] colors, int colorOffset, int nPaint);
1688    private static native void nativeDrawVertices(int nCanvas, int mode, int n,
1689                   float[] verts, int vertOffset, float[] texs, int texOffset,
1690                   int[] colors, int colorOffset, short[] indices,
1691                   int indexOffset, int indexCount, int nPaint);
1692
1693    private static native void native_drawText(int nativeCanvas, char[] text,
1694                                               int index, int count, float x,
1695                                               float y, int flags, int paint);
1696    private static native void native_drawText(int nativeCanvas, String text,
1697                                               int start, int end, float x,
1698                                               float y, int flags, int paint);
1699
1700    private static native void native_drawTextRun(int nativeCanvas, String text,
1701            int start, int end, int contextStart, int contextEnd,
1702            float x, float y, int flags, int paint);
1703
1704    private static native void native_drawTextRun(int nativeCanvas, char[] text,
1705            int start, int count, int contextStart, int contextCount,
1706            float x, float y, int flags, int paint);
1707
1708    private static native void native_drawPosText(int nativeCanvas,
1709                                                  char[] text, int index,
1710                                                  int count, float[] pos,
1711                                                  int paint);
1712    private static native void native_drawPosText(int nativeCanvas,
1713                                                  String text, float[] pos,
1714                                                  int paint);
1715    private static native void native_drawTextOnPath(int nativeCanvas,
1716                                                     char[] text, int index,
1717                                                     int count, int path,
1718                                                     float hOffset,
1719                                                     float vOffset, int paint);
1720    private static native void native_drawTextOnPath(int nativeCanvas,
1721                                                     String text, int path,
1722                                                     float hOffset,
1723                                                     float vOffset, int paint);
1724    private static native void native_drawPicture(int nativeCanvas,
1725                                                  int nativePicture);
1726    private static native void finalizer(int nativeCanvas);
1727}
1728