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