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