Canvas.java revision 6d9fe5bd22b531bfce69b146254a4791c76acddc
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 *
33 * <div class="special reference">
34 * <h3>Developer Guides</h3>
35 * <p>For more information about how to use Canvas, read the
36 * <a href="{@docRoot}guide/topics/graphics/2d-graphics.html">
37 * Canvas and Drawables</a> developer guide.</p></div>
38 */
39public class Canvas {
40    // assigned in constructors or setBitmap, freed in finalizer
41    int mNativeCanvas;
42
43    // may be null
44    private Bitmap mBitmap;
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    // Maximum bitmap size as defined in Skia's native code
66    // (see SkCanvas.cpp, SkDraw.cpp)
67    private static final int MAXMIMUM_BITMAP_SIZE = 32766;
68
69    // This field is used to finalize the native Canvas properly
70    @SuppressWarnings({"UnusedDeclaration"})
71    private final CanvasFinalizer mFinalizer;
72
73    private static class CanvasFinalizer {
74        private int mNativeCanvas;
75
76        public CanvasFinalizer(int nativeCanvas) {
77            mNativeCanvas = nativeCanvas;
78        }
79
80        @Override
81        protected void finalize() throws Throwable {
82            try {
83                if (mNativeCanvas != 0) {
84                    finalizer(mNativeCanvas);
85                }
86            } finally {
87                super.finalize();
88            }
89        }
90    }
91
92    /**
93     * Construct an empty raster canvas. Use setBitmap() to specify a bitmap to
94     * draw into.  The initial target density is {@link Bitmap#DENSITY_NONE};
95     * this will typically be replaced when a target bitmap is set for the
96     * canvas.
97     */
98    public Canvas() {
99        // 0 means no native bitmap
100        mNativeCanvas = initRaster(0);
101        mFinalizer = new CanvasFinalizer(mNativeCanvas);
102    }
103
104    /**
105     * Construct a canvas with the specified bitmap to draw into. The bitmap
106     * must be mutable.
107     *
108     * <p>The initial target density of the canvas is the same as the given
109     * bitmap's density.
110     *
111     * @param bitmap Specifies a mutable bitmap for the canvas to draw into.
112     */
113    public Canvas(Bitmap bitmap) {
114        if (!bitmap.isMutable()) {
115            throw new IllegalStateException("Immutable bitmap passed to Canvas constructor");
116        }
117        throwIfRecycled(bitmap);
118        mNativeCanvas = initRaster(bitmap.ni());
119        mFinalizer = new CanvasFinalizer(mNativeCanvas);
120        mBitmap = bitmap;
121        mDensity = bitmap.mDensity;
122    }
123
124    Canvas(int nativeCanvas) {
125        if (nativeCanvas == 0) {
126            throw new IllegalStateException();
127        }
128        mNativeCanvas = nativeCanvas;
129        mFinalizer = new CanvasFinalizer(nativeCanvas);
130        mDensity = Bitmap.getDefaultDensity();
131    }
132
133    /**
134     * Replace existing canvas while ensuring that the swap has occurred before
135     * the previous native canvas is unreferenced.
136     */
137    private void safeCanvasSwap(int nativeCanvas) {
138        final int oldCanvas = mNativeCanvas;
139        mNativeCanvas = nativeCanvas;
140        mFinalizer.mNativeCanvas = nativeCanvas;
141        finalizer(oldCanvas);
142    }
143
144    /**
145     * Returns null.
146     *
147     * @deprecated This method is not supported and should not be invoked.
148     *
149     * @hide
150     */
151    @Deprecated
152    protected GL getGL() {
153        return null;
154    }
155
156    /**
157     * Indicates whether this Canvas uses hardware acceleration.
158     *
159     * Note that this method does not define what type of hardware acceleration
160     * may or may not be used.
161     *
162     * @return True if drawing operations are hardware accelerated,
163     *         false otherwise.
164     */
165    public boolean isHardwareAccelerated() {
166        return false;
167    }
168
169    /**
170     * Specify a bitmap for the canvas to draw into. As a side-effect, the
171     * canvas' target density is updated to match that of the bitmap while all
172     * other state such as the layers, filters, matrix, and clip are reset.
173     *
174     * @param bitmap Specifies a mutable bitmap for the canvas to draw into.
175     * @see #setDensity(int)
176     * @see #getDensity()
177     */
178    public void setBitmap(Bitmap bitmap) {
179        if (isHardwareAccelerated()) {
180            throw new RuntimeException("Can't set a bitmap device on a GL canvas");
181        }
182
183        if (bitmap == null) {
184            safeCanvasSwap(initRaster(0));
185            mDensity = Bitmap.DENSITY_NONE;
186        } else {
187            if (!bitmap.isMutable()) {
188                throw new IllegalStateException();
189            }
190            throwIfRecycled(bitmap);
191
192            safeCanvasSwap(initRaster(bitmap.ni()));
193            mDensity = bitmap.mDensity;
194        }
195
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, Paint paint,
359            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, int alpha,
390            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     * <strong>Note:</strong> it is recommended to use {@link #concat(Matrix)},
495     * {@link #scale(float, float)}, {@link #translate(float, float)} and
496     * {@link #rotate(float)} instead of this method.
497     *
498     * @param matrix The matrix to replace the current matrix with. If it is
499     *               null, set the current matrix to identity.
500     *
501     * @see #concat(Matrix)
502     */
503    public void setMatrix(Matrix matrix) {
504        native_setMatrix(mNativeCanvas,
505                         matrix == null ? 0 : matrix.native_instance);
506    }
507
508    /**
509     * Return, in ctm, the current transformation matrix. This does not alter
510     * the matrix in the canvas, but just returns a copy of it.
511     */
512    @Deprecated
513    public void getMatrix(Matrix ctm) {
514        native_getCTM(mNativeCanvas, ctm.native_instance);
515    }
516
517    /**
518     * Return a new matrix with a copy of the canvas' current transformation
519     * matrix.
520     */
521    @Deprecated
522    public final Matrix getMatrix() {
523        Matrix m = new Matrix();
524        //noinspection deprecation
525        getMatrix(m);
526        return m;
527    }
528
529    /**
530     * Modify the current clip with the specified rectangle.
531     *
532     * @param rect The rect to intersect with the current clip
533     * @param op How the clip is modified
534     * @return true if the resulting clip is non-empty
535     */
536    public boolean clipRect(RectF rect, Region.Op op) {
537        return native_clipRect(mNativeCanvas, rect.left, rect.top, rect.right, rect.bottom,
538                op.nativeInt);
539    }
540
541    /**
542     * Modify the current clip with the specified rectangle, which is
543     * expressed in local coordinates.
544     *
545     * @param rect The rectangle to intersect with the current clip.
546     * @param op How the clip is modified
547     * @return true if the resulting clip is non-empty
548     */
549    public boolean clipRect(Rect rect, Region.Op op) {
550        return native_clipRect(mNativeCanvas, rect.left, rect.top, rect.right, rect.bottom,
551                op.nativeInt);
552    }
553
554    /**
555     * Intersect the current clip with the specified rectangle, which is
556     * expressed in local coordinates.
557     *
558     * @param rect The rectangle to intersect with the current clip.
559     * @return true if the resulting clip is non-empty
560     */
561    public native boolean clipRect(RectF rect);
562
563    /**
564     * Intersect the current clip with the specified rectangle, which is
565     * expressed in local coordinates.
566     *
567     * @param rect The rectangle to intersect with the current clip.
568     * @return true if the resulting clip is non-empty
569     */
570    public native boolean clipRect(Rect rect);
571
572    /**
573     * Modify the current clip with the specified rectangle, which is
574     * expressed in local coordinates.
575     *
576     * @param left   The left side of the rectangle to intersect with the
577     *               current clip
578     * @param top    The top of the rectangle to intersect with the current
579     *               clip
580     * @param right  The right side of the rectangle to intersect with the
581     *               current clip
582     * @param bottom The bottom of the rectangle to intersect with the current
583     *               clip
584     * @param op     How the clip is modified
585     * @return       true if the resulting clip is non-empty
586     */
587    public boolean clipRect(float left, float top, float right, float bottom, Region.Op op) {
588        return native_clipRect(mNativeCanvas, left, top, right, bottom, op.nativeInt);
589    }
590
591    /**
592     * Intersect the current clip with the specified rectangle, which is
593     * expressed in local coordinates.
594     *
595     * @param left   The left side of the rectangle to intersect with the
596     *               current clip
597     * @param top    The top of the rectangle to intersect with the current clip
598     * @param right  The right side of the rectangle to intersect with the
599     *               current clip
600     * @param bottom The bottom of the rectangle to intersect with the current
601     *               clip
602     * @return       true if the resulting clip is non-empty
603     */
604    public native boolean clipRect(float left, float top, float right, float bottom);
605
606    /**
607     * Intersect the current clip with the specified rectangle, which is
608     * expressed in local coordinates.
609     *
610     * @param left   The left side of the rectangle to intersect with the
611     *               current clip
612     * @param top    The top of the rectangle to intersect with the current clip
613     * @param right  The right side of the rectangle to intersect with the
614     *               current clip
615     * @param bottom The bottom of the rectangle to intersect with the current
616     *               clip
617     * @return       true if the resulting clip is non-empty
618     */
619    public native boolean clipRect(int left, int top, int right, int bottom);
620
621    /**
622        * Modify the current clip with the specified path.
623     *
624     * @param path The path to operate on the current clip
625     * @param op   How the clip is modified
626     * @return     true if the resulting is non-empty
627     */
628    public boolean clipPath(Path path, Region.Op op) {
629        return native_clipPath(mNativeCanvas, path.ni(), op.nativeInt);
630    }
631
632    /**
633     * Intersect the current clip with the specified path.
634     *
635     * @param path The path to intersect with the current clip
636     * @return     true if the resulting is non-empty
637     */
638    public boolean clipPath(Path path) {
639        return clipPath(path, Region.Op.INTERSECT);
640    }
641
642    /**
643     * Modify the current clip with the specified region. Note that unlike
644     * clipRect() and clipPath() which transform their arguments by the
645     * current matrix, clipRegion() assumes its argument is already in the
646     * coordinate system of the current layer's bitmap, and so not
647     * transformation is performed.
648     *
649     * @param region The region to operate on the current clip, based on op
650     * @param op How the clip is modified
651     * @return true if the resulting is non-empty
652     */
653    public boolean clipRegion(Region region, Region.Op op) {
654        return native_clipRegion(mNativeCanvas, region.ni(), op.nativeInt);
655    }
656
657    /**
658     * Intersect the current clip with the specified region. Note that unlike
659     * clipRect() and clipPath() which transform their arguments by the
660     * current matrix, clipRegion() assumes its argument is already in the
661     * coordinate system of the current layer's bitmap, and so not
662     * transformation is performed.
663     *
664     * @param region The region to operate on the current clip, based on op
665     * @return true if the resulting is non-empty
666     */
667    public boolean clipRegion(Region region) {
668        return clipRegion(region, Region.Op.INTERSECT);
669    }
670
671    public DrawFilter getDrawFilter() {
672        return mDrawFilter;
673    }
674
675    public void setDrawFilter(DrawFilter filter) {
676        int nativeFilter = 0;
677        if (filter != null) {
678            nativeFilter = filter.mNativeInt;
679        }
680        mDrawFilter = filter;
681        nativeSetDrawFilter(mNativeCanvas, nativeFilter);
682    }
683
684    public enum EdgeType {
685        BW(0),  //!< treat edges by just rounding to nearest pixel boundary
686        AA(1);  //!< treat edges by rounding-out, since they may be antialiased
687
688        EdgeType(int nativeInt) {
689            this.nativeInt = nativeInt;
690        }
691
692        /**
693         * @hide
694         */
695        public final int nativeInt;
696    }
697
698    /**
699     * Return true if the specified rectangle, after being transformed by the
700     * current matrix, would lie completely outside of the current clip. Call
701     * this to check if an area you intend to draw into is clipped out (and
702     * therefore you can skip making the draw calls).
703     *
704     * @param rect  the rect to compare with the current clip
705     * @param type  specifies how to treat the edges (BW or antialiased)
706     * @return      true if the rect (transformed by the canvas' matrix)
707     *              does not intersect with the canvas' clip
708     */
709    public boolean quickReject(RectF rect, EdgeType type) {
710        return native_quickReject(mNativeCanvas, rect);
711    }
712
713    /**
714     * Return true if the specified path, after being transformed by the
715     * current matrix, would lie completely outside of the current clip. Call
716     * this to check if an area you intend to draw into is clipped out (and
717     * therefore you can skip making the draw calls). Note: for speed it may
718     * return false even if the path itself might not intersect the clip
719     * (i.e. the bounds of the path intersects, but the path does not).
720     *
721     * @param path        The path to compare with the current clip
722     * @param type        true if the path should be considered antialiased,
723     *                    since that means it may
724     *                    affect a larger area (more pixels) than
725     *                    non-antialiased.
726     * @return            true if the path (transformed by the canvas' matrix)
727     *                    does not intersect with the canvas' clip
728     */
729    public boolean quickReject(Path path, EdgeType type) {
730        return native_quickReject(mNativeCanvas, path.ni());
731    }
732
733    /**
734     * Return true if the specified rectangle, after being transformed by the
735     * current matrix, would lie completely outside of the current clip. Call
736     * this to check if an area you intend to draw into is clipped out (and
737     * therefore you can skip making the draw calls).
738     *
739     * @param left        The left side of the rectangle to compare with the
740     *                    current clip
741     * @param top         The top of the rectangle to compare with the current
742     *                    clip
743     * @param right       The right side of the rectangle to compare with the
744     *                    current clip
745     * @param bottom      The bottom of the rectangle to compare with the
746     *                    current clip
747     * @param type        true if the rect should be considered antialiased,
748     *                    since that means it may affect a larger area (more
749     *                    pixels) than non-antialiased.
750     * @return            true if the rect (transformed by the canvas' matrix)
751     *                    does not intersect with the canvas' clip
752     */
753    public boolean quickReject(float left, float top, float right, float bottom,
754                               EdgeType type) {
755        return native_quickReject(mNativeCanvas, left, top, right, bottom);
756    }
757
758    /**
759     * Retrieve the clip bounds, returning true if they are non-empty.
760     *
761     * @param bounds Return the clip bounds here. If it is null, ignore it but
762     *               still return true if the current clip is non-empty.
763     * @return true if the current clip is non-empty.
764     */
765    public boolean getClipBounds(Rect bounds) {
766        return native_getClipBounds(mNativeCanvas, bounds);
767    }
768
769    /**
770     * Retrieve the clip bounds.
771     *
772     * @return the clip bounds, or [0, 0, 0, 0] if the clip is empty.
773     */
774    public final Rect getClipBounds() {
775        Rect r = new Rect();
776        getClipBounds(r);
777        return r;
778    }
779
780    /**
781     * Fill the entire canvas' bitmap (restricted to the current clip) with the
782     * specified RGB color, using srcover porterduff mode.
783     *
784     * @param r red component (0..255) of the color to draw onto the canvas
785     * @param g green component (0..255) of the color to draw onto the canvas
786     * @param b blue component (0..255) of the color to draw onto the canvas
787     */
788    public void drawRGB(int r, int g, int b) {
789        native_drawRGB(mNativeCanvas, r, g, b);
790    }
791
792    /**
793     * Fill the entire canvas' bitmap (restricted to the current clip) with the
794     * specified ARGB color, using srcover porterduff mode.
795     *
796     * @param a alpha component (0..255) of the color to draw onto the canvas
797     * @param r red component (0..255) of the color to draw onto the canvas
798     * @param g green component (0..255) of the color to draw onto the canvas
799     * @param b blue component (0..255) of the color to draw onto the canvas
800     */
801    public void drawARGB(int a, int r, int g, int b) {
802        native_drawARGB(mNativeCanvas, a, r, g, b);
803    }
804
805    /**
806     * Fill the entire canvas' bitmap (restricted to the current clip) with the
807     * specified color, using srcover porterduff mode.
808     *
809     * @param color the color to draw onto the canvas
810     */
811    public void drawColor(int color) {
812        native_drawColor(mNativeCanvas, color);
813    }
814
815    /**
816     * Fill the entire canvas' bitmap (restricted to the current clip) with the
817     * specified color and porter-duff xfermode.
818     *
819     * @param color the color to draw with
820     * @param mode  the porter-duff mode to apply to the color
821     */
822    public void drawColor(int color, PorterDuff.Mode mode) {
823        native_drawColor(mNativeCanvas, color, mode.nativeInt);
824    }
825
826    /**
827     * Fill the entire canvas' bitmap (restricted to the current clip) with
828     * the specified paint. This is equivalent (but faster) to drawing an
829     * infinitely large rectangle with the specified paint.
830     *
831     * @param paint The paint used to draw onto the canvas
832     */
833    public void drawPaint(Paint paint) {
834        native_drawPaint(mNativeCanvas, paint.mNativePaint);
835    }
836
837    /**
838     * Draw a series of points. Each point is centered at the coordinate
839     * specified by pts[], and its diameter is specified by the paint's stroke
840     * width (as transformed by the canvas' CTM), with special treatment for
841     * a stroke width of 0, which always draws exactly 1 pixel (or at most 4
842     * if antialiasing is enabled). The shape of the point is controlled by
843     * the paint's Cap type. The shape is a square, unless the cap type is
844     * Round, in which case the shape is a circle.
845     *
846     * @param pts      Array of points to draw [x0 y0 x1 y1 x2 y2 ...]
847     * @param offset   Number of values to skip before starting to draw.
848     * @param count    The number of values to process, after skipping offset
849     *                 of them. Since one point uses two values, the number of
850     *                 "points" that are drawn is really (count >> 1).
851     * @param paint    The paint used to draw the points
852     */
853    public native void drawPoints(float[] pts, int offset, int count, Paint paint);
854
855    /**
856     * Helper for drawPoints() that assumes you want to draw the entire array
857     */
858    public void drawPoints(float[] pts, Paint paint) {
859        drawPoints(pts, 0, pts.length, paint);
860    }
861
862    /**
863     * Helper for drawPoints() for drawing a single point.
864     */
865    public native void drawPoint(float x, float y, Paint paint);
866
867    /**
868     * Draw a line segment with the specified start and stop x,y coordinates,
869     * using the specified paint. NOTE: since a line is always "framed", the
870     * Style is ignored in the paint.
871     *
872     * @param startX The x-coordinate of the start point of the line
873     * @param startY The y-coordinate of the start point of the line
874     * @param paint  The paint used to draw the line
875     */
876    public void drawLine(float startX, float startY, float stopX, float stopY, Paint paint) {
877        native_drawLine(mNativeCanvas, startX, startY, stopX, stopY, paint.mNativePaint);
878    }
879
880    /**
881     * Draw a series of lines. Each line is taken from 4 consecutive values
882     * in the pts array. Thus to draw 1 line, the array must contain at least 4
883     * values. This is logically the same as drawing the array as follows:
884     * drawLine(pts[0], pts[1], pts[2], pts[3]) followed by
885     * drawLine(pts[4], pts[5], pts[6], pts[7]) and so on.
886     *
887     * @param pts      Array of points to draw [x0 y0 x1 y1 x2 y2 ...]
888     * @param offset   Number of values in the array to skip before drawing.
889     * @param count    The number of values in the array to process, after
890     *                 skipping "offset" of them. Since each line uses 4 values,
891     *                 the number of "lines" that are drawn is really
892     *                 (count >> 2).
893     * @param paint    The paint used to draw the points
894     */
895    public native void drawLines(float[] pts, int offset, int count, Paint paint);
896
897    public void drawLines(float[] pts, Paint paint) {
898        drawLines(pts, 0, pts.length, paint);
899    }
900
901    /**
902     * Draw the specified Rect using the specified paint. The rectangle will
903     * be filled or framed based on the Style in the paint.
904     *
905     * @param rect  The rect to be drawn
906     * @param paint The paint used to draw the rect
907     */
908    public void drawRect(RectF rect, Paint paint) {
909        native_drawRect(mNativeCanvas, rect, paint.mNativePaint);
910    }
911
912    /**
913     * Draw the specified Rect using the specified Paint. The rectangle
914     * will be filled or framed based on the Style in the paint.
915     *
916     * @param r        The rectangle to be drawn.
917     * @param paint    The paint used to draw the rectangle
918     */
919    public void drawRect(Rect r, Paint paint) {
920        drawRect(r.left, r.top, r.right, r.bottom, paint);
921    }
922
923
924    /**
925     * Draw the specified Rect using the specified paint. The rectangle will
926     * be filled or framed based on the Style in the paint.
927     *
928     * @param left   The left side of the rectangle to be drawn
929     * @param top    The top side of the rectangle to be drawn
930     * @param right  The right side of the rectangle to be drawn
931     * @param bottom The bottom side of the rectangle to be drawn
932     * @param paint  The paint used to draw the rect
933     */
934    public void drawRect(float left, float top, float right, float bottom, Paint paint) {
935        native_drawRect(mNativeCanvas, left, top, right, bottom, paint.mNativePaint);
936    }
937
938    /**
939     * Draw the specified oval using the specified paint. The oval will be
940     * filled or framed based on the Style in the paint.
941     *
942     * @param oval The rectangle bounds of the oval to be drawn
943     */
944    public void drawOval(RectF oval, Paint paint) {
945        if (oval == null) {
946            throw new NullPointerException();
947        }
948        native_drawOval(mNativeCanvas, oval, paint.mNativePaint);
949    }
950
951    /**
952     * Draw the specified circle using the specified paint. If radius is <= 0,
953     * then nothing will be drawn. The circle will be filled or framed based
954     * on the Style in the paint.
955     *
956     * @param cx     The x-coordinate of the center of the cirle to be drawn
957     * @param cy     The y-coordinate of the center of the cirle to be drawn
958     * @param radius The radius of the cirle to be drawn
959     * @param paint  The paint used to draw the circle
960     */
961    public void drawCircle(float cx, float cy, float radius, Paint paint) {
962        native_drawCircle(mNativeCanvas, cx, cy, radius, paint.mNativePaint);
963    }
964
965    /**
966     * <p>Draw the specified arc, which will be scaled to fit inside the
967     * specified oval.</p>
968     *
969     * <p>If the start angle is negative or >= 360, the start angle is treated
970     * as start angle modulo 360.</p>
971     *
972     * <p>If the sweep angle is >= 360, then the oval is drawn
973     * completely. Note that this differs slightly from SkPath::arcTo, which
974     * treats the sweep angle modulo 360. If the sweep angle is negative,
975     * the sweep angle is treated as sweep angle modulo 360</p>
976     *
977     * <p>The arc is drawn clockwise. An angle of 0 degrees correspond to the
978     * geometric angle of 0 degrees (3 o'clock on a watch.)</p>
979     *
980     * @param oval       The bounds of oval used to define the shape and size
981     *                   of the arc
982     * @param startAngle Starting angle (in degrees) where the arc begins
983     * @param sweepAngle Sweep angle (in degrees) measured clockwise
984     * @param useCenter If true, include the center of the oval in the arc, and
985                        close it if it is being stroked. This will draw a wedge
986     * @param paint      The paint used to draw the arc
987     */
988    public void drawArc(RectF oval, float startAngle, float sweepAngle, boolean useCenter,
989            Paint paint) {
990        if (oval == null) {
991            throw new NullPointerException();
992        }
993        native_drawArc(mNativeCanvas, oval, startAngle, sweepAngle,
994                       useCenter, paint.mNativePaint);
995    }
996
997    /**
998     * Draw the specified round-rect using the specified paint. The roundrect
999     * will be filled or framed based on the Style in the paint.
1000     *
1001     * @param rect  The rectangular bounds of the roundRect to be drawn
1002     * @param rx    The x-radius of the oval used to round the corners
1003     * @param ry    The y-radius of the oval used to round the corners
1004     * @param paint The paint used to draw the roundRect
1005     */
1006    public void drawRoundRect(RectF rect, float rx, float ry, Paint paint) {
1007        if (rect == null) {
1008            throw new NullPointerException();
1009        }
1010        native_drawRoundRect(mNativeCanvas, rect, rx, ry,
1011                             paint.mNativePaint);
1012    }
1013
1014    /**
1015     * Draw the specified path using the specified paint. The path will be
1016     * filled or framed based on the Style in the paint.
1017     *
1018     * @param path  The path to be drawn
1019     * @param paint The paint used to draw the path
1020     */
1021    public void drawPath(Path path, Paint paint) {
1022        native_drawPath(mNativeCanvas, path.ni(), paint.mNativePaint);
1023    }
1024
1025    private static void throwIfRecycled(Bitmap bitmap) {
1026        if (bitmap.isRecycled()) {
1027            throw new RuntimeException("Canvas: trying to use a recycled bitmap " + bitmap);
1028        }
1029    }
1030
1031    /**
1032     * Draws the specified bitmap as an N-patch (most often, a 9-patches.)
1033     *
1034     * Note: Only supported by hardware accelerated canvas at the moment.
1035     *
1036     * @param bitmap The bitmap to draw as an N-patch
1037     * @param chunks The patches information (matches the native struct Res_png_9patch)
1038     * @param dst The destination rectangle.
1039     * @param paint The paint to draw the bitmap with. may be null
1040     *
1041     * @hide
1042     */
1043    public void drawPatch(Bitmap bitmap, byte[] chunks, RectF dst, Paint paint) {
1044    }
1045
1046    /**
1047     * Draw the specified bitmap, with its top/left corner at (x,y), using
1048     * the specified paint, transformed by the current matrix.
1049     *
1050     * <p>Note: if the paint contains a maskfilter that generates a mask which
1051     * extends beyond the bitmap's original width/height (e.g. BlurMaskFilter),
1052     * then the bitmap will be drawn as if it were in a Shader with CLAMP mode.
1053     * Thus the color outside of the original width/height will be the edge
1054     * color replicated.
1055     *
1056     * <p>If the bitmap and canvas have different densities, this function
1057     * will take care of automatically scaling the bitmap to draw at the
1058     * same density as the canvas.
1059     *
1060     * @param bitmap The bitmap to be drawn
1061     * @param left   The position of the left side of the bitmap being drawn
1062     * @param top    The position of the top side of the bitmap being drawn
1063     * @param paint  The paint used to draw the bitmap (may be null)
1064     */
1065    public void drawBitmap(Bitmap bitmap, float left, float top, Paint paint) {
1066        throwIfRecycled(bitmap);
1067        native_drawBitmap(mNativeCanvas, bitmap.ni(), left, top,
1068                paint != null ? paint.mNativePaint : 0, mDensity, mScreenDensity, bitmap.mDensity);
1069    }
1070
1071    /**
1072     * Draw the specified bitmap, scaling/translating automatically to fill
1073     * the destination rectangle. If the source rectangle is not null, it
1074     * specifies the subset of the bitmap to draw.
1075     *
1076     * <p>Note: if the paint contains a maskfilter that generates a mask which
1077     * extends beyond the bitmap's original width/height (e.g. BlurMaskFilter),
1078     * then the bitmap will be drawn as if it were in a Shader with CLAMP mode.
1079     * Thus the color outside of the original width/height will be the edge
1080     * color replicated.
1081     *
1082     * <p>This function <em>ignores the density associated with the bitmap</em>.
1083     * This is because the source and destination rectangle coordinate
1084     * spaces are in their respective densities, so must already have the
1085     * appropriate scaling factor applied.
1086     *
1087     * @param bitmap The bitmap to be drawn
1088     * @param src    May be null. The subset of the bitmap to be drawn
1089     * @param dst    The rectangle that the bitmap will be scaled/translated
1090     *               to fit into
1091     * @param paint  May be null. The paint used to draw the bitmap
1092     */
1093    public void drawBitmap(Bitmap bitmap, Rect src, RectF dst, Paint paint) {
1094        if (dst == null) {
1095            throw new NullPointerException();
1096        }
1097        throwIfRecycled(bitmap);
1098        native_drawBitmap(mNativeCanvas, bitmap.ni(), src, dst,
1099                          paint != null ? paint.mNativePaint : 0, mScreenDensity, bitmap.mDensity);
1100    }
1101
1102    /**
1103     * Draw the specified bitmap, scaling/translating automatically to fill
1104     * the destination rectangle. If the source rectangle is not null, it
1105     * specifies the subset of the bitmap to draw.
1106     *
1107     * <p>Note: if the paint contains a maskfilter that generates a mask which
1108     * extends beyond the bitmap's original width/height (e.g. BlurMaskFilter),
1109     * then the bitmap will be drawn as if it were in a Shader with CLAMP mode.
1110     * Thus the color outside of the original width/height will be the edge
1111     * color replicated.
1112     *
1113     * <p>This function <em>ignores the density associated with the bitmap</em>.
1114     * This is because the source and destination rectangle coordinate
1115     * spaces are in their respective densities, so must already have the
1116     * appropriate scaling factor applied.
1117     *
1118     * @param bitmap The bitmap to be drawn
1119     * @param src    May be null. The subset of the bitmap to be drawn
1120     * @param dst    The rectangle that the bitmap will be scaled/translated
1121     *               to fit into
1122     * @param paint  May be null. The paint used to draw the bitmap
1123     */
1124    public void drawBitmap(Bitmap bitmap, Rect src, Rect dst, Paint paint) {
1125        if (dst == null) {
1126            throw new NullPointerException();
1127        }
1128        throwIfRecycled(bitmap);
1129        native_drawBitmap(mNativeCanvas, bitmap.ni(), src, dst,
1130                          paint != null ? paint.mNativePaint : 0, mScreenDensity, bitmap.mDensity);
1131    }
1132
1133    /**
1134     * Treat the specified array of colors as a bitmap, and draw it. This gives
1135     * the same result as first creating a bitmap from the array, and then
1136     * drawing it, but this method avoids explicitly creating a bitmap object
1137     * which can be more efficient if the colors are changing often.
1138     *
1139     * @param colors Array of colors representing the pixels of the bitmap
1140     * @param offset Offset into the array of colors for the first pixel
1141     * @param stride The number of colors in the array between rows (must be
1142     *               >= width or <= -width).
1143     * @param x The X coordinate for where to draw the bitmap
1144     * @param y The Y coordinate for where to draw the bitmap
1145     * @param width The width of the bitmap
1146     * @param height The height of the bitmap
1147     * @param hasAlpha True if the alpha channel of the colors contains valid
1148     *                 values. If false, the alpha byte is ignored (assumed to
1149     *                 be 0xFF for every pixel).
1150     * @param paint  May be null. The paint used to draw the bitmap
1151     */
1152    public void drawBitmap(int[] colors, int offset, int stride, float x, float y,
1153            int width, int height, boolean hasAlpha, Paint paint) {
1154        // check for valid input
1155        if (width < 0) {
1156            throw new IllegalArgumentException("width must be >= 0");
1157        }
1158        if (height < 0) {
1159            throw new IllegalArgumentException("height must be >= 0");
1160        }
1161        if (Math.abs(stride) < width) {
1162            throw new IllegalArgumentException("abs(stride) must be >= width");
1163        }
1164        int lastScanline = offset + (height - 1) * stride;
1165        int length = colors.length;
1166        if (offset < 0 || (offset + width > length) || lastScanline < 0
1167                || (lastScanline + width > length)) {
1168            throw new ArrayIndexOutOfBoundsException();
1169        }
1170        // quick escape if there's nothing to draw
1171        if (width == 0 || height == 0) {
1172            return;
1173        }
1174        // punch down to native for the actual draw
1175        native_drawBitmap(mNativeCanvas, colors, offset, stride, x, y, width, height, hasAlpha,
1176                paint != null ? paint.mNativePaint : 0);
1177    }
1178
1179    /** Legacy version of drawBitmap(int[] colors, ...) that took ints for x,y
1180     */
1181    public void drawBitmap(int[] colors, int offset, int stride, int x, int y,
1182            int width, int height, boolean hasAlpha, Paint paint) {
1183        // call through to the common float version
1184        drawBitmap(colors, offset, stride, (float)x, (float)y, width, height,
1185                   hasAlpha, paint);
1186    }
1187
1188    /**
1189     * Draw the bitmap using the specified matrix.
1190     *
1191     * @param bitmap The bitmap to draw
1192     * @param matrix The matrix used to transform the bitmap when it is drawn
1193     * @param paint  May be null. The paint used to draw the bitmap
1194     */
1195    public void drawBitmap(Bitmap bitmap, Matrix matrix, Paint paint) {
1196        nativeDrawBitmapMatrix(mNativeCanvas, bitmap.ni(), matrix.ni(),
1197                paint != null ? paint.mNativePaint : 0);
1198    }
1199
1200    /**
1201     * @hide
1202     */
1203    protected static void checkRange(int length, int offset, int count) {
1204        if ((offset | count) < 0 || offset + count > length) {
1205            throw new ArrayIndexOutOfBoundsException();
1206        }
1207    }
1208
1209    /**
1210     * Draw the bitmap through the mesh, where mesh vertices are evenly
1211     * distributed across the bitmap. There are meshWidth+1 vertices across, and
1212     * meshHeight+1 vertices down. The verts array is accessed in row-major
1213     * order, so that the first meshWidth+1 vertices are distributed across the
1214     * top of the bitmap from left to right. A more general version of this
1215     * methid is drawVertices().
1216     *
1217     * @param bitmap The bitmap to draw using the mesh
1218     * @param meshWidth The number of columns in the mesh. Nothing is drawn if
1219     *                  this is 0
1220     * @param meshHeight The number of rows in the mesh. Nothing is drawn if
1221     *                   this is 0
1222     * @param verts Array of x,y pairs, specifying where the mesh should be
1223     *              drawn. There must be at least
1224     *              (meshWidth+1) * (meshHeight+1) * 2 + meshOffset values
1225     *              in the array
1226     * @param vertOffset Number of verts elements to skip before drawing
1227     * @param colors May be null. Specifies a color at each vertex, which is
1228     *               interpolated across the cell, and whose values are
1229     *               multiplied by the corresponding bitmap colors. If not null,
1230     *               there must be at least (meshWidth+1) * (meshHeight+1) +
1231     *               colorOffset values in the array.
1232     * @param colorOffset Number of color elements to skip before drawing
1233     * @param paint  May be null. The paint used to draw the bitmap
1234     */
1235    public void drawBitmapMesh(Bitmap bitmap, int meshWidth, int meshHeight,
1236            float[] verts, int vertOffset, int[] colors, int colorOffset, Paint paint) {
1237        if ((meshWidth | meshHeight | vertOffset | colorOffset) < 0) {
1238            throw new ArrayIndexOutOfBoundsException();
1239        }
1240        if (meshWidth == 0 || meshHeight == 0) {
1241            return;
1242        }
1243        int count = (meshWidth + 1) * (meshHeight + 1);
1244        // we mul by 2 since we need two floats per vertex
1245        checkRange(verts.length, vertOffset, count * 2);
1246        if (colors != null) {
1247            // no mul by 2, since we need only 1 color per vertex
1248            checkRange(colors.length, colorOffset, count);
1249        }
1250        nativeDrawBitmapMesh(mNativeCanvas, bitmap.ni(), meshWidth, meshHeight,
1251                             verts, vertOffset, colors, colorOffset,
1252                             paint != null ? paint.mNativePaint : 0);
1253    }
1254
1255    public enum VertexMode {
1256        TRIANGLES(0),
1257        TRIANGLE_STRIP(1),
1258        TRIANGLE_FAN(2);
1259
1260        VertexMode(int nativeInt) {
1261            this.nativeInt = nativeInt;
1262        }
1263
1264        /**
1265         * @hide
1266         */
1267        public final int nativeInt;
1268    }
1269
1270    /**
1271     * Draw the array of vertices, interpreted as triangles (based on mode). The
1272     * verts array is required, and specifies the x,y pairs for each vertex. If
1273     * texs is non-null, then it is used to specify the coordinate in shader
1274     * coordinates to use at each vertex (the paint must have a shader in this
1275     * case). If there is no texs array, but there is a color array, then each
1276     * color is interpolated across its corresponding triangle in a gradient. If
1277     * both texs and colors arrays are present, then they behave as before, but
1278     * the resulting color at each pixels is the result of multiplying the
1279     * colors from the shader and the color-gradient together. The indices array
1280     * is optional, but if it is present, then it is used to specify the index
1281     * of each triangle, rather than just walking through the arrays in order.
1282     *
1283     * @param mode How to interpret the array of vertices
1284     * @param vertexCount The number of values in the vertices array (and
1285     *      corresponding texs and colors arrays if non-null). Each logical
1286     *      vertex is two values (x, y), vertexCount must be a multiple of 2.
1287     * @param verts Array of vertices for the mesh
1288     * @param vertOffset Number of values in the verts to skip before drawing.
1289     * @param texs May be null. If not null, specifies the coordinates to sample
1290     *      into the current shader (e.g. bitmap tile or gradient)
1291     * @param texOffset Number of values in texs to skip before drawing.
1292     * @param colors May be null. If not null, specifies a color for each
1293     *      vertex, to be interpolated across the triangle.
1294     * @param colorOffset Number of values in colors to skip before drawing.
1295     * @param indices If not null, array of indices to reference into the
1296     *      vertex (texs, colors) array.
1297     * @param indexCount number of entries in the indices array (if not null).
1298     * @param paint Specifies the shader to use if the texs array is non-null.
1299     */
1300    public void drawVertices(VertexMode mode, int vertexCount, float[] verts, int vertOffset,
1301            float[] texs, int texOffset, int[] colors, int colorOffset,
1302            short[] indices, int indexOffset, int indexCount, Paint paint) {
1303        checkRange(verts.length, vertOffset, vertexCount);
1304        if (texs != null) {
1305            checkRange(texs.length, texOffset, vertexCount);
1306        }
1307        if (colors != null) {
1308            checkRange(colors.length, colorOffset, vertexCount / 2);
1309        }
1310        if (indices != null) {
1311            checkRange(indices.length, indexOffset, indexCount);
1312        }
1313        nativeDrawVertices(mNativeCanvas, mode.nativeInt, vertexCount, verts,
1314                           vertOffset, texs, texOffset, colors, colorOffset,
1315                          indices, indexOffset, indexCount, paint.mNativePaint);
1316    }
1317
1318    /**
1319     * Draw the text, with origin at (x,y), using the specified paint. The
1320     * origin is interpreted based on the Align setting in the paint.
1321     *
1322     * @param text  The text to be drawn
1323     * @param x     The x-coordinate of the origin of the text being drawn
1324     * @param y     The y-coordinate of the origin of the text being drawn
1325     * @param paint The paint used for the text (e.g. color, size, style)
1326     */
1327    public void drawText(char[] text, int index, int count, float x, float y, Paint paint) {
1328        if ((index | count | (index + count) |
1329            (text.length - index - count)) < 0) {
1330            throw new IndexOutOfBoundsException();
1331        }
1332        native_drawText(mNativeCanvas, text, index, count, x, y, paint.mNativePaint);
1333    }
1334
1335    /**
1336     * Draw the text, with origin at (x,y), using the specified paint. The
1337     * origin is interpreted based on the Align setting in the paint.
1338     *
1339     * @param text  The text to be drawn
1340     * @param x     The x-coordinate of the origin of the text being drawn
1341     * @param y     The y-coordinate of the origin of the text being drawn
1342     * @param paint The paint used for the text (e.g. color, size, style)
1343     */
1344    public void drawText(String text, float x, float y, Paint paint) {
1345        native_drawText(mNativeCanvas, text, 0, text.length(), x, y, paint.mNativePaint);
1346    }
1347
1348    /**
1349     * Draw the text, with origin at (x,y), using the specified paint.
1350     * The origin is interpreted based on the Align setting in the paint.
1351     *
1352     * @param text  The text to be drawn
1353     * @param start The index of the first character in text to draw
1354     * @param end   (end - 1) is the index of the last character in text to draw
1355     * @param x     The x-coordinate of the origin of the text being drawn
1356     * @param y     The y-coordinate of the origin of the text being drawn
1357     * @param paint The paint used for the text (e.g. color, size, style)
1358     */
1359    public void drawText(String text, int start, int end, float x, float y, Paint paint) {
1360        if ((start | end | (end - start) | (text.length() - end)) < 0) {
1361            throw new IndexOutOfBoundsException();
1362        }
1363        native_drawText(mNativeCanvas, text, start, end, x, y, paint.mNativePaint);
1364    }
1365
1366    /**
1367     * Draw the specified range of text, specified by start/end, with its
1368     * origin at (x,y), in the specified Paint. The origin is interpreted
1369     * based on the Align setting in the Paint.
1370     *
1371     * @param text     The text to be drawn
1372     * @param start    The index of the first character in text to draw
1373     * @param end      (end - 1) is the index of the last character in text
1374     *                 to draw
1375     * @param x        The x-coordinate of origin for where to draw the text
1376     * @param y        The y-coordinate of origin for where to draw the text
1377     * @param paint The paint used for the text (e.g. color, size, style)
1378     */
1379    public void drawText(CharSequence text, int start, int end, float x, float y, Paint paint) {
1380        if (text instanceof String || text instanceof SpannedString ||
1381            text instanceof SpannableString) {
1382            native_drawText(mNativeCanvas, text.toString(), start, end, x, y, paint.mNativePaint);
1383        } else if (text instanceof GraphicsOperations) {
1384            ((GraphicsOperations) text).drawText(this, start, end, x, y,
1385                                                     paint);
1386        } else {
1387            char[] buf = TemporaryBuffer.obtain(end - start);
1388            TextUtils.getChars(text, start, end, buf, 0);
1389            native_drawText(mNativeCanvas, buf, 0, end - start, x, y, paint.mNativePaint);
1390            TemporaryBuffer.recycle(buf);
1391        }
1392    }
1393
1394    /**
1395     * Render a run of all LTR or all RTL text, with shaping. This does not run
1396     * bidi on the provided text, but renders it as a uniform right-to-left or
1397     * left-to-right run, as indicated by dir. Alignment of the text is as
1398     * determined by the Paint's TextAlign value.
1399     *
1400     * @param text the text to render
1401     * @param index the start of the text to render
1402     * @param count the count of chars to render
1403     * @param contextIndex the start of the context for shaping.  Must be
1404     *         no greater than index.
1405     * @param contextCount the number of characters in the context for shaping.
1406     *         ContexIndex + contextCount must be no less than index
1407     *         + count.
1408     * @param x the x position at which to draw the text
1409     * @param y the y position at which to draw the text
1410     * @param paint the paint
1411     * @hide
1412     */
1413    public void drawTextRun(char[] text, int index, int count, int contextIndex, int contextCount,
1414            float x, float y, Paint paint) {
1415
1416        if (text == null) {
1417            throw new NullPointerException("text is null");
1418        }
1419        if (paint == null) {
1420            throw new NullPointerException("paint is null");
1421        }
1422        if ((index | count | text.length - index - count) < 0) {
1423            throw new IndexOutOfBoundsException();
1424        }
1425
1426        native_drawTextRun(mNativeCanvas, text, index, count,
1427                contextIndex, contextCount, x, y, paint.mNativePaint);
1428    }
1429
1430    /**
1431     * Render a run of all LTR or all RTL text, with shaping. This does not run
1432     * bidi on the provided text, but renders it as a uniform right-to-left or
1433     * left-to-right run, as indicated by dir. Alignment of the text is as
1434     * determined by the Paint's TextAlign value.
1435     *
1436     * @param text the text to render
1437     * @param start the start of the text to render. Data before this position
1438     *            can be used for shaping context.
1439     * @param end the end of the text to render. Data at or after this
1440     *            position can be used for shaping context.
1441     * @param x the x position at which to draw the text
1442     * @param y the y position at which to draw the text
1443     * @param paint the paint
1444     * @hide
1445     */
1446    public void drawTextRun(CharSequence text, int start, int end, int contextStart, int contextEnd,
1447            float x, float y, Paint paint) {
1448
1449        if (text == null) {
1450            throw new NullPointerException("text is null");
1451        }
1452        if (paint == null) {
1453            throw new NullPointerException("paint is null");
1454        }
1455        if ((start | end | end - start | text.length() - end) < 0) {
1456            throw new IndexOutOfBoundsException();
1457        }
1458
1459        if (text instanceof String || text instanceof SpannedString ||
1460                text instanceof SpannableString) {
1461            native_drawTextRun(mNativeCanvas, text.toString(), start, end,
1462                    contextStart, contextEnd, x, y, paint.mNativePaint);
1463        } else if (text instanceof GraphicsOperations) {
1464            ((GraphicsOperations) text).drawTextRun(this, start, end,
1465                    contextStart, contextEnd, x, y, paint);
1466        } else {
1467            int contextLen = contextEnd - contextStart;
1468            int len = end - start;
1469            char[] buf = TemporaryBuffer.obtain(contextLen);
1470            TextUtils.getChars(text, contextStart, contextEnd, buf, 0);
1471            native_drawTextRun(mNativeCanvas, buf, start - contextStart, len,
1472                    0, contextLen, x, y, paint.mNativePaint);
1473            TemporaryBuffer.recycle(buf);
1474        }
1475    }
1476
1477    /**
1478     * Draw the text in the array, with each character's origin specified by
1479     * the pos array.
1480     *
1481     * This method does not support glyph composition and decomposition and
1482     * should therefore not be used to render complex scripts.
1483     *
1484     * @param text     The text to be drawn
1485     * @param index    The index of the first character to draw
1486     * @param count    The number of characters to draw, starting from index.
1487     * @param pos      Array of [x,y] positions, used to position each
1488     *                 character
1489     * @param paint    The paint used for the text (e.g. color, size, style)
1490     */
1491    @Deprecated
1492    public void drawPosText(char[] text, int index, int count, float[] pos, Paint paint) {
1493        if (index < 0 || index + count > text.length || count*2 > pos.length) {
1494            throw new IndexOutOfBoundsException();
1495        }
1496        native_drawPosText(mNativeCanvas, text, index, count, pos,
1497                           paint.mNativePaint);
1498    }
1499
1500    /**
1501     * Draw the text in the array, with each character's origin specified by
1502     * the pos array.
1503     *
1504     * This method does not support glyph composition and decomposition and
1505     * should therefore not be used to render complex scripts.
1506     *
1507     * @param text  The text to be drawn
1508     * @param pos   Array of [x,y] positions, used to position each character
1509     * @param paint The paint used for the text (e.g. color, size, style)
1510     */
1511    @Deprecated
1512    public void drawPosText(String text, float[] pos, Paint paint) {
1513        if (text.length()*2 > pos.length) {
1514            throw new ArrayIndexOutOfBoundsException();
1515        }
1516        native_drawPosText(mNativeCanvas, text, pos, paint.mNativePaint);
1517    }
1518
1519    /**
1520     * Draw the text, with origin at (x,y), using the specified paint, along
1521     * the specified path. The paint's Align setting determins where along the
1522     * path to start the text.
1523     *
1524     * @param text     The text to be drawn
1525     * @param path     The path the text should follow for its baseline
1526     * @param hOffset  The distance along the path to add to the text's
1527     *                 starting position
1528     * @param vOffset  The distance above(-) or below(+) the path to position
1529     *                 the text
1530     * @param paint    The paint used for the text (e.g. color, size, style)
1531     */
1532    public void drawTextOnPath(char[] text, int index, int count, Path path,
1533            float hOffset, float vOffset, Paint paint) {
1534        if (index < 0 || index + count > text.length) {
1535            throw new ArrayIndexOutOfBoundsException();
1536        }
1537        native_drawTextOnPath(mNativeCanvas, text, index, count,
1538                              path.ni(), hOffset, vOffset, paint.mNativePaint);
1539    }
1540
1541    /**
1542     * Draw the text, with origin at (x,y), using the specified paint, along
1543     * the specified path. The paint's Align setting determins where along the
1544     * path to start the text.
1545     *
1546     * @param text     The text to be drawn
1547     * @param path     The path the text should follow for its baseline
1548     * @param hOffset  The distance along the path to add to the text's
1549     *                 starting position
1550     * @param vOffset  The distance above(-) or below(+) the path to position
1551     *                 the text
1552     * @param paint    The paint used for the text (e.g. color, size, style)
1553     */
1554    public void drawTextOnPath(String text, Path path, float hOffset, float vOffset, Paint paint) {
1555        if (text.length() > 0) {
1556            native_drawTextOnPath(mNativeCanvas, text, path.ni(), hOffset, vOffset,
1557                    paint.mNativePaint);
1558        }
1559    }
1560
1561    /**
1562     * Save the canvas state, draw the picture, and restore the canvas state.
1563     * This differs from picture.draw(canvas), which does not perform any
1564     * save/restore.
1565     *
1566     * @param picture  The picture to be drawn
1567     */
1568    public void drawPicture(Picture picture) {
1569        picture.endRecording();
1570        native_drawPicture(mNativeCanvas, picture.ni());
1571    }
1572
1573    /**
1574     * Draw the picture, stretched to fit into the dst rectangle.
1575     */
1576    public void drawPicture(Picture picture, RectF dst) {
1577        save();
1578        translate(dst.left, dst.top);
1579        if (picture.getWidth() > 0 && picture.getHeight() > 0) {
1580            scale(dst.width() / picture.getWidth(), dst.height() / picture.getHeight());
1581        }
1582        drawPicture(picture);
1583        restore();
1584    }
1585
1586    /**
1587     * Draw the picture, stretched to fit into the dst rectangle.
1588     */
1589    public void drawPicture(Picture picture, Rect dst) {
1590        save();
1591        translate(dst.left, dst.top);
1592        if (picture.getWidth() > 0 && picture.getHeight() > 0) {
1593            scale((float) dst.width() / picture.getWidth(),
1594                    (float) dst.height() / picture.getHeight());
1595        }
1596        drawPicture(picture);
1597        restore();
1598    }
1599
1600    /**
1601     * Free up as much memory as possible from private caches (e.g. fonts, images)
1602     *
1603     * @hide
1604     */
1605    public static native void freeCaches();
1606
1607    /**
1608     * Free up text layout caches
1609     *
1610     * @hide
1611     */
1612    public static native void freeTextLayoutCaches();
1613
1614    private static native int initRaster(int nativeBitmapOrZero);
1615    private static native int native_saveLayer(int nativeCanvas, RectF bounds,
1616                                               int paint, int layerFlags);
1617    private static native int native_saveLayer(int nativeCanvas, float l,
1618                                               float t, float r, float b,
1619                                               int paint, int layerFlags);
1620    private static native int native_saveLayerAlpha(int nativeCanvas,
1621                                                    RectF bounds, int alpha,
1622                                                    int layerFlags);
1623    private static native int native_saveLayerAlpha(int nativeCanvas, float l,
1624                                                    float t, float r, float b,
1625                                                    int alpha, int layerFlags);
1626
1627    private static native void native_concat(int nCanvas, int nMatrix);
1628    private static native void native_setMatrix(int nCanvas, int nMatrix);
1629    private static native boolean native_clipRect(int nCanvas,
1630                                                  float left, float top,
1631                                                  float right, float bottom,
1632                                                  int regionOp);
1633    private static native boolean native_clipPath(int nativeCanvas,
1634                                                  int nativePath,
1635                                                  int regionOp);
1636    private static native boolean native_clipRegion(int nativeCanvas,
1637                                                    int nativeRegion,
1638                                                    int regionOp);
1639    private static native void nativeSetDrawFilter(int nativeCanvas,
1640                                                   int nativeFilter);
1641    private static native boolean native_getClipBounds(int nativeCanvas,
1642                                                       Rect bounds);
1643    private static native void native_getCTM(int canvas, int matrix);
1644    private static native boolean native_quickReject(int nativeCanvas,
1645                                                     RectF rect);
1646    private static native boolean native_quickReject(int nativeCanvas,
1647                                                     int path);
1648    private static native boolean native_quickReject(int nativeCanvas,
1649                                                     float left, float top,
1650                                                     float right, float bottom);
1651    private static native void native_drawRGB(int nativeCanvas, int r, int g,
1652                                              int b);
1653    private static native void native_drawARGB(int nativeCanvas, int a, int r,
1654                                               int g, int b);
1655    private static native void native_drawColor(int nativeCanvas, int color);
1656    private static native void native_drawColor(int nativeCanvas, int color,
1657                                                int mode);
1658    private static native void native_drawPaint(int nativeCanvas, int paint);
1659    private static native void native_drawLine(int nativeCanvas, float startX,
1660                                               float startY, float stopX,
1661                                               float stopY, int paint);
1662    private static native void native_drawRect(int nativeCanvas, RectF rect,
1663                                               int paint);
1664    private static native void native_drawRect(int nativeCanvas, float left,
1665                                               float top, float right,
1666                                               float bottom, int paint);
1667    private static native void native_drawOval(int nativeCanvas, RectF oval,
1668                                               int paint);
1669    private static native void native_drawCircle(int nativeCanvas, float cx,
1670                                                 float cy, float radius,
1671                                                 int paint);
1672    private static native void native_drawArc(int nativeCanvas, RectF oval,
1673                                              float startAngle, float sweep,
1674                                              boolean useCenter, int paint);
1675    private static native void native_drawRoundRect(int nativeCanvas,
1676                                                    RectF rect, float rx,
1677                                                    float ry, int paint);
1678    private static native void native_drawPath(int nativeCanvas, int path,
1679                                               int paint);
1680    private native void native_drawBitmap(int nativeCanvas, int bitmap,
1681                                                 float left, float top,
1682                                                 int nativePaintOrZero,
1683                                                 int canvasDensity,
1684                                                 int screenDensity,
1685                                                 int bitmapDensity);
1686    private native void native_drawBitmap(int nativeCanvas, int bitmap,
1687                                                 Rect src, RectF dst,
1688                                                 int nativePaintOrZero,
1689                                                 int screenDensity,
1690                                                 int bitmapDensity);
1691    private static native void native_drawBitmap(int nativeCanvas, int bitmap,
1692                                                 Rect src, Rect dst,
1693                                                 int nativePaintOrZero,
1694                                                 int screenDensity,
1695                                                 int bitmapDensity);
1696    private static native void native_drawBitmap(int nativeCanvas, int[] colors,
1697                                                int offset, int stride, float x,
1698                                                 float y, int width, int height,
1699                                                 boolean hasAlpha,
1700                                                 int nativePaintOrZero);
1701    private static native void nativeDrawBitmapMatrix(int nCanvas, int nBitmap,
1702                                                      int nMatrix, int nPaint);
1703    private static native void nativeDrawBitmapMesh(int nCanvas, int nBitmap,
1704                                                    int meshWidth, int meshHeight,
1705                                                    float[] verts, int vertOffset,
1706                                                    int[] colors, int colorOffset, int nPaint);
1707    private static native void nativeDrawVertices(int nCanvas, int mode, int n,
1708                   float[] verts, int vertOffset, float[] texs, int texOffset,
1709                   int[] colors, int colorOffset, short[] indices,
1710                   int indexOffset, int indexCount, int nPaint);
1711
1712    private static native void native_drawText(int nativeCanvas, char[] text,
1713                                               int index, int count, float x,
1714                                               float y, int paint);
1715    private static native void native_drawText(int nativeCanvas, String text,
1716                                               int start, int end, float x,
1717                                               float y, int paint);
1718
1719    private static native void native_drawTextRun(int nativeCanvas, String text,
1720            int start, int end, int contextStart, int contextEnd,
1721            float x, float y, int paint);
1722
1723    private static native void native_drawTextRun(int nativeCanvas, char[] text,
1724            int start, int count, int contextStart, int contextCount,
1725            float x, float y, int paint);
1726
1727    private static native void native_drawPosText(int nativeCanvas,
1728                                                  char[] text, int index,
1729                                                  int count, float[] pos,
1730                                                  int paint);
1731    private static native void native_drawPosText(int nativeCanvas,
1732                                                  String text, float[] pos,
1733                                                  int paint);
1734    private static native void native_drawTextOnPath(int nativeCanvas,
1735                                                     char[] text, int index,
1736                                                     int count, int path,
1737                                                     float hOffset,
1738                                                     float vOffset,
1739                                                     int paint);
1740    private static native void native_drawTextOnPath(int nativeCanvas,
1741                                                     String text, int path,
1742                                                     float hOffset,
1743                                                     float vOffset,
1744                                                     int paint);
1745    private static native void native_drawPicture(int nativeCanvas,
1746                                                  int nativePicture);
1747    private static native void finalizer(int nativeCanvas);
1748}
1749