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