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