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