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