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