Canvas.java revision 0c702b88c5d0d4380930b920f5be6e66dd95a0d8
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        final int nativeInt;
657    }
658
659    /**
660     * Return true if the specified rectangle, after being transformed by the
661     * current matrix, would lie completely outside of the current clip. Call
662     * this to check if an area you intend to draw into is clipped out (and
663     * therefore you can skip making the draw calls).
664     *
665     * @param rect  the rect to compare with the current clip
666     * @param type  specifies how to treat the edges (BW or antialiased)
667     * @return      true if the rect (transformed by the canvas' matrix)
668     *              does not intersect with the canvas' clip
669     */
670    public boolean quickReject(RectF rect, EdgeType type) {
671        return native_quickReject(mNativeCanvas, rect, type.nativeInt);
672    }
673
674    /**
675     * Return true if the specified path, after being transformed by the
676     * current matrix, would lie completely outside of the current clip. Call
677     * this to check if an area you intend to draw into is clipped out (and
678     * therefore you can skip making the draw calls). Note: for speed it may
679     * return false even if the path itself might not intersect the clip
680     * (i.e. the bounds of the path intersects, but the path does not).
681     *
682     * @param path        The path to compare with the current clip
683     * @param type        true if the path should be considered antialiased,
684     *                    since that means it may
685     *                    affect a larger area (more pixels) than
686     *                    non-antialiased.
687     * @return            true if the path (transformed by the canvas' matrix)
688     *                    does not intersect with the canvas' clip
689     */
690    public boolean quickReject(Path path, EdgeType type) {
691        return native_quickReject(mNativeCanvas, path.ni(), type.nativeInt);
692    }
693
694    /**
695     * Return true if the specified rectangle, after being transformed by the
696     * current matrix, would lie completely outside of the current clip. Call
697     * this to check if an area you intend to draw into is clipped out (and
698     * therefore you can skip making the draw calls).
699     *
700     * @param left        The left side of the rectangle to compare with the
701     *                    current clip
702     * @param top         The top of the rectangle to compare with the current
703     *                    clip
704     * @param right       The right side of the rectangle to compare with the
705     *                    current clip
706     * @param bottom      The bottom of the rectangle to compare with the
707     *                    current clip
708     * @param type        true if the rect should be considered antialiased,
709     *                    since that means it may affect a larger area (more
710     *                    pixels) than non-antialiased.
711     * @return            true if the rect (transformed by the canvas' matrix)
712     *                    does not intersect with the canvas' clip
713     */
714    public boolean quickReject(float left, float top, float right, float bottom,
715                               EdgeType type) {
716        return native_quickReject(mNativeCanvas, left, top, right, bottom,
717                                  type.nativeInt);
718    }
719
720    /**
721     * Retrieve the clip bounds, returning true if they are non-empty.
722     *
723     * @param bounds Return the clip bounds here. If it is null, ignore it but
724     *               still return true if the current clip is non-empty.
725     * @return true if the current clip is non-empty.
726     */
727    public boolean getClipBounds(Rect bounds) {
728        return native_getClipBounds(mNativeCanvas, bounds);
729    }
730
731    /**
732     * Retrieve the clip bounds.
733     *
734     * @return the clip bounds, or [0, 0, 0, 0] if the clip is empty.
735     */
736    public final Rect getClipBounds() {
737        Rect r = new Rect();
738        getClipBounds(r);
739        return r;
740    }
741
742    /**
743     * Fill the entire canvas' bitmap (restricted to the current clip) with the
744     * specified RGB color, using srcover porterduff mode.
745     *
746     * @param r red component (0..255) of the color to draw onto the canvas
747     * @param g green component (0..255) of the color to draw onto the canvas
748     * @param b blue component (0..255) of the color to draw onto the canvas
749     */
750    public void drawRGB(int r, int g, int b) {
751        native_drawRGB(mNativeCanvas, r, g, b);
752    }
753
754    /**
755     * Fill the entire canvas' bitmap (restricted to the current clip) with the
756     * specified ARGB color, using srcover porterduff mode.
757     *
758     * @param a alpha component (0..255) of the color to draw onto the canvas
759     * @param r red component (0..255) of the color to draw onto the canvas
760     * @param g green component (0..255) of the color to draw onto the canvas
761     * @param b blue component (0..255) of the color to draw onto the canvas
762     */
763    public void drawARGB(int a, int r, int g, int b) {
764        native_drawARGB(mNativeCanvas, a, r, g, b);
765    }
766
767    /**
768     * Fill the entire canvas' bitmap (restricted to the current clip) with the
769     * specified color, using srcover porterduff mode.
770     *
771     * @param color the color to draw onto the canvas
772     */
773    public void drawColor(int color) {
774        native_drawColor(mNativeCanvas, color);
775    }
776
777    /**
778     * Fill the entire canvas' bitmap (restricted to the current clip) with the
779     * specified color and porter-duff xfermode.
780     *
781     * @param color the color to draw with
782     * @param mode  the porter-duff mode to apply to the color
783     */
784    public void drawColor(int color, PorterDuff.Mode mode) {
785        native_drawColor(mNativeCanvas, color, mode.nativeInt);
786    }
787
788    /**
789     * Fill the entire canvas' bitmap (restricted to the current clip) with
790     * the specified paint. This is equivalent (but faster) to drawing an
791     * infinitely large rectangle with the specified paint.
792     *
793     * @param paint The paint used to draw onto the canvas
794     */
795    public void drawPaint(Paint paint) {
796        native_drawPaint(mNativeCanvas, paint.mNativePaint);
797    }
798
799    /**
800     * Draw a series of points. Each point is centered at the coordinate
801     * specified by pts[], and its diameter is specified by the paint's stroke
802     * width (as transformed by the canvas' CTM), with special treatment for
803     * a stroke width of 0, which always draws exactly 1 pixel (or at most 4
804     * if antialiasing is enabled). The shape of the point is controlled by
805     * the paint's Cap type. The shape is a square, unless the cap type is
806     * Round, in which case the shape is a circle.
807     *
808     * @param pts      Array of points to draw [x0 y0 x1 y1 x2 y2 ...]
809     * @param offset   Number of values to skip before starting to draw.
810     * @param count    The number of values to process, after skipping offset
811     *                 of them. Since one point uses two values, the number of
812     *                 "points" that are drawn is really (count >> 1).
813     * @param paint    The paint used to draw the points
814     */
815    public native void drawPoints(float[] pts, int offset, int count,
816                                  Paint paint);
817
818    /**
819     * Helper for drawPoints() that assumes you want to draw the entire array
820     */
821    public void drawPoints(float[] pts, Paint paint) {
822        drawPoints(pts, 0, pts.length, paint);
823    }
824
825    /**
826     * Helper for drawPoints() for drawing a single point.
827     */
828    public native void drawPoint(float x, float y, Paint paint);
829
830    /**
831     * Draw a line segment with the specified start and stop x,y coordinates,
832     * using the specified paint. NOTE: since a line is always "framed", the
833     * Style is ignored in the paint.
834     *
835     * @param startX The x-coordinate of the start point of the line
836     * @param startY The y-coordinate of the start point of the line
837     * @param paint  The paint used to draw the line
838     */
839    public void drawLine(float startX, float startY, float stopX, float stopY,
840                         Paint paint) {
841        native_drawLine(mNativeCanvas, startX, startY, stopX, stopY,
842                        paint.mNativePaint);
843    }
844
845    /**
846     * Draw a series of lines. Each line is taken from 4 consecutive values
847     * in the pts array. Thus to draw 1 line, the array must contain at least 4
848     * values. This is logically the same as drawing the array as follows:
849     * drawLine(pts[0], pts[1], pts[2], pts[3]) followed by
850     * drawLine(pts[4], pts[5], pts[6], pts[7]) and so on.
851     *
852     * @param pts      Array of points to draw [x0 y0 x1 y1 x2 y2 ...]
853     * @param offset   Number of values in the array to skip before drawing.
854     * @param count    The number of values in the array to process, after
855     *                 skipping "offset" of them. Since each line uses 4 values,
856     *                 the number of "lines" that are drawn is really
857     *                 (count >> 2).
858     * @param paint    The paint used to draw the points
859     */
860    public native void drawLines(float[] pts, int offset, int count,
861                                 Paint paint);
862
863    public void drawLines(float[] pts, Paint paint) {
864        drawLines(pts, 0, pts.length, paint);
865    }
866
867    /**
868     * Draw the specified Rect using the specified paint. The rectangle will
869     * be filled or framed based on the Style in the paint.
870     *
871     * @param rect  The rect to be drawn
872     * @param paint The paint used to draw the rect
873     */
874    public void drawRect(RectF rect, Paint paint) {
875        native_drawRect(mNativeCanvas, rect, paint.mNativePaint);
876    }
877
878    /**
879     * Draw the specified Rect using the specified Paint. The rectangle
880     * will be filled or framed based on the Style in the paint.
881     *
882     * @param r        The rectangle to be drawn.
883     * @param paint    The paint used to draw the rectangle
884     */
885    public void drawRect(Rect r, Paint paint) {
886        drawRect(r.left, r.top, r.right, r.bottom, paint);
887    }
888
889
890    /**
891     * Draw the specified Rect using the specified paint. The rectangle will
892     * be filled or framed based on the Style in the paint.
893     *
894     * @param left   The left side of the rectangle to be drawn
895     * @param top    The top side of the rectangle to be drawn
896     * @param right  The right side of the rectangle to be drawn
897     * @param bottom The bottom side of the rectangle to be drawn
898     * @param paint  The paint used to draw the rect
899     */
900    public void drawRect(float left, float top, float right, float bottom,
901                         Paint paint) {
902        native_drawRect(mNativeCanvas, left, top, right, bottom,
903                        paint.mNativePaint);
904    }
905
906    /**
907     * Draw the specified oval using the specified paint. The oval will be
908     * filled or framed based on the Style in the paint.
909     *
910     * @param oval The rectangle bounds of the oval to be drawn
911     */
912    public void drawOval(RectF oval, Paint paint) {
913        if (oval == null) {
914            throw new NullPointerException();
915        }
916        native_drawOval(mNativeCanvas, oval, paint.mNativePaint);
917    }
918
919    /**
920     * Draw the specified circle using the specified paint. If radius is <= 0,
921     * then nothing will be drawn. The circle will be filled or framed based
922     * on the Style in the paint.
923     *
924     * @param cx     The x-coordinate of the center of the cirle to be drawn
925     * @param cy     The y-coordinate of the center of the cirle to be drawn
926     * @param radius The radius of the cirle to be drawn
927     * @param paint  The paint used to draw the circle
928     */
929    public void drawCircle(float cx, float cy, float radius, Paint paint) {
930        native_drawCircle(mNativeCanvas, cx, cy, radius,
931                          paint.mNativePaint);
932    }
933
934    /**
935     * Draw the specified arc, which will be scaled to fit inside the
936     * specified oval. If the sweep angle is >= 360, then the oval is drawn
937     * completely. Note that this differs slightly from SkPath::arcTo, which
938     * treats the sweep angle mod 360.
939     *
940     * @param oval       The bounds of oval used to define the shape and size
941     *                   of the arc
942     * @param startAngle Starting angle (in degrees) where the arc begins
943     * @param sweepAngle Sweep angle (in degrees) measured clockwise
944     * @param useCenter If true, include the center of the oval in the arc, and
945                        close it if it is being stroked. This will draw a wedge
946     * @param paint      The paint used to draw the arc
947     */
948    public void drawArc(RectF oval, float startAngle, float sweepAngle,
949                        boolean useCenter, Paint paint) {
950        if (oval == null) {
951            throw new NullPointerException();
952        }
953        native_drawArc(mNativeCanvas, oval, startAngle, sweepAngle,
954                       useCenter, paint.mNativePaint);
955    }
956
957    /**
958     * Draw the specified round-rect using the specified paint. The roundrect
959     * will be filled or framed based on the Style in the paint.
960     *
961     * @param rect  The rectangular bounds of the roundRect to be drawn
962     * @param rx    The x-radius of the oval used to round the corners
963     * @param ry    The y-radius of the oval used to round the corners
964     * @param paint The paint used to draw the roundRect
965     */
966    public void drawRoundRect(RectF rect, float rx, float ry, Paint paint) {
967        if (rect == null) {
968            throw new NullPointerException();
969        }
970        native_drawRoundRect(mNativeCanvas, rect, rx, ry,
971                             paint.mNativePaint);
972    }
973
974    /**
975     * Draw the specified path using the specified paint. The path will be
976     * filled or framed based on the Style in the paint.
977     *
978     * @param path  The path to be drawn
979     * @param paint The paint used to draw the path
980     */
981    public void drawPath(Path path, Paint paint) {
982        native_drawPath(mNativeCanvas, path.ni(), paint.mNativePaint);
983    }
984
985    private static void throwIfRecycled(Bitmap bitmap) {
986        if (bitmap.isRecycled()) {
987            throw new RuntimeException(
988                        "Canvas: trying to use a recycled bitmap " + bitmap);
989        }
990    }
991
992    /**
993     * Draw the specified bitmap, with its top/left corner at (x,y), using
994     * the specified paint, transformed by the current matrix.
995     *
996     * <p>Note: if the paint contains a maskfilter that generates a mask which
997     * extends beyond the bitmap's original width/height (e.g. BlurMaskFilter),
998     * then the bitmap will be drawn as if it were in a Shader with CLAMP mode.
999     * Thus the color outside of the original width/height will be the edge
1000     * color replicated.
1001     *
1002     * <p>If the bitmap and canvas have different densities, this function
1003     * will take care of automatically scaling the bitmap to draw at the
1004     * same density as the canvas.
1005     *
1006     * @param bitmap The bitmap to be drawn
1007     * @param left   The position of the left side of the bitmap being drawn
1008     * @param top    The position of the top side of the bitmap being drawn
1009     * @param paint  The paint used to draw the bitmap (may be null)
1010     */
1011    public void drawBitmap(Bitmap bitmap, float left, float top, Paint paint) {
1012        throwIfRecycled(bitmap);
1013        native_drawBitmap(mNativeCanvas, bitmap.ni(), left, top,
1014                paint != null ? paint.mNativePaint : 0, mDensity, mScreenDensity,
1015                bitmap.mDensity);
1016    }
1017
1018    /**
1019     * Draw the specified bitmap, scaling/translating automatically to fill
1020     * the destination rectangle. If the source rectangle is not null, it
1021     * specifies the subset of the bitmap to draw.
1022     *
1023     * <p>Note: if the paint contains a maskfilter that generates a mask which
1024     * extends beyond the bitmap's original width/height (e.g. BlurMaskFilter),
1025     * then the bitmap will be drawn as if it were in a Shader with CLAMP mode.
1026     * Thus the color outside of the original width/height will be the edge
1027     * color replicated.
1028     *
1029     * <p>This function <em>ignores the density associated with the bitmap</em>.
1030     * This is because the source and destination rectangle coordinate
1031     * spaces are in their respective densities, so must already have the
1032     * appropriate scaling factor applied.
1033     *
1034     * @param bitmap The bitmap to be drawn
1035     * @param src    May be null. The subset of the bitmap to be drawn
1036     * @param dst    The rectangle that the bitmap will be scaled/translated
1037     *               to fit into
1038     * @param paint  May be null. The paint used to draw the bitmap
1039     */
1040    public void drawBitmap(Bitmap bitmap, Rect src, RectF dst, Paint paint) {
1041        if (dst == null) {
1042            throw new NullPointerException();
1043        }
1044        throwIfRecycled(bitmap);
1045        native_drawBitmap(mNativeCanvas, bitmap.ni(), src, dst,
1046                          paint != null ? paint.mNativePaint : 0,
1047                          mScreenDensity, bitmap.mDensity);
1048    }
1049
1050    /**
1051     * Draw the specified bitmap, scaling/translating automatically to fill
1052     * the destination rectangle. If the source rectangle is not null, it
1053     * specifies the subset of the bitmap to draw.
1054     *
1055     * <p>Note: if the paint contains a maskfilter that generates a mask which
1056     * extends beyond the bitmap's original width/height (e.g. BlurMaskFilter),
1057     * then the bitmap will be drawn as if it were in a Shader with CLAMP mode.
1058     * Thus the color outside of the original width/height will be the edge
1059     * color replicated.
1060     *
1061     * <p>This function <em>ignores the density associated with the bitmap</em>.
1062     * This is because the source and destination rectangle coordinate
1063     * spaces are in their respective densities, so must already have the
1064     * appropriate scaling factor applied.
1065     *
1066     * @param bitmap The bitmap to be drawn
1067     * @param src    May be null. The subset of the bitmap to be drawn
1068     * @param dst    The rectangle that the bitmap will be scaled/translated
1069     *               to fit into
1070     * @param paint  May be null. The paint used to draw the bitmap
1071     */
1072    public void drawBitmap(Bitmap bitmap, Rect src, Rect dst, Paint paint) {
1073        if (dst == null) {
1074            throw new NullPointerException();
1075        }
1076        throwIfRecycled(bitmap);
1077        native_drawBitmap(mNativeCanvas, bitmap.ni(), src, dst,
1078                          paint != null ? paint.mNativePaint : 0,
1079                          mScreenDensity, bitmap.mDensity);
1080    }
1081
1082    /**
1083     * Treat the specified array of colors as a bitmap, and draw it. This gives
1084     * the same result as first creating a bitmap from the array, and then
1085     * drawing it, but this method avoids explicitly creating a bitmap object
1086     * which can be more efficient if the colors are changing often.
1087     *
1088     * @param colors Array of colors representing the pixels of the bitmap
1089     * @param offset Offset into the array of colors for the first pixel
1090     * @param stride The number of of colors in the array between rows (must be
1091     *               >= width or <= -width).
1092     * @param x The X coordinate for where to draw the bitmap
1093     * @param y The Y coordinate for where to draw the bitmap
1094     * @param width The width of the bitmap
1095     * @param height The height of the bitmap
1096     * @param hasAlpha True if the alpha channel of the colors contains valid
1097     *                 values. If false, the alpha byte is ignored (assumed to
1098     *                 be 0xFF for every pixel).
1099     * @param paint  May be null. The paint used to draw the bitmap
1100     */
1101    public void drawBitmap(int[] colors, int offset, int stride, float x,
1102                           float y, int width, int height, boolean hasAlpha,
1103                           Paint paint) {
1104        // check for valid input
1105        if (width < 0) {
1106            throw new IllegalArgumentException("width must be >= 0");
1107        }
1108        if (height < 0) {
1109            throw new IllegalArgumentException("height must be >= 0");
1110        }
1111        if (Math.abs(stride) < width) {
1112            throw new IllegalArgumentException("abs(stride) must be >= width");
1113        }
1114        int lastScanline = offset + (height - 1) * stride;
1115        int length = colors.length;
1116        if (offset < 0 || (offset + width > length) || lastScanline < 0
1117                || (lastScanline + width > length)) {
1118            throw new ArrayIndexOutOfBoundsException();
1119        }
1120        // quick escape if there's nothing to draw
1121        if (width == 0 || height == 0) {
1122            return;
1123        }
1124        // punch down to native for the actual draw
1125        native_drawBitmap(mNativeCanvas, colors, offset, stride, x, y, width, height, hasAlpha,
1126                paint != null ? paint.mNativePaint : 0);
1127    }
1128
1129    /** Legacy version of drawBitmap(int[] colors, ...) that took ints for x,y
1130     */
1131    public void drawBitmap(int[] colors, int offset, int stride, int x, int y,
1132                           int width, int height, boolean hasAlpha,
1133                           Paint paint) {
1134        // call through to the common float version
1135        drawBitmap(colors, offset, stride, (float)x, (float)y, width, height,
1136                   hasAlpha, paint);
1137    }
1138
1139    /**
1140     * Draw the bitmap using the specified matrix.
1141     *
1142     * @param bitmap The bitmap to draw
1143     * @param matrix The matrix used to transform the bitmap when it is drawn
1144     * @param paint  May be null. The paint used to draw the bitmap
1145     */
1146    public void drawBitmap(Bitmap bitmap, Matrix matrix, Paint paint) {
1147        nativeDrawBitmapMatrix(mNativeCanvas, bitmap.ni(), matrix.ni(),
1148                paint != null ? paint.mNativePaint : 0);
1149    }
1150
1151    private static void checkRange(int length, int offset, int count) {
1152        if ((offset | count) < 0 || offset + count > length) {
1153            throw new ArrayIndexOutOfBoundsException();
1154        }
1155    }
1156
1157    /**
1158     * Draw the bitmap through the mesh, where mesh vertices are evenly
1159     * distributed across the bitmap. There are meshWidth+1 vertices across, and
1160     * meshHeight+1 vertices down. The verts array is accessed in row-major
1161     * order, so that the first meshWidth+1 vertices are distributed across the
1162     * top of the bitmap from left to right. A more general version of this
1163     * methid is drawVertices().
1164     *
1165     * @param bitmap The bitmap to draw using the mesh
1166     * @param meshWidth The number of columns in the mesh. Nothing is drawn if
1167     *                  this is 0
1168     * @param meshHeight The number of rows in the mesh. Nothing is drawn if
1169     *                   this is 0
1170     * @param verts Array of x,y pairs, specifying where the mesh should be
1171     *              drawn. There must be at least
1172     *              (meshWidth+1) * (meshHeight+1) * 2 + meshOffset values
1173     *              in the array
1174     * @param vertOffset Number of verts elements to skip before drawing
1175     * @param colors May be null. Specifies a color at each vertex, which is
1176     *               interpolated across the cell, and whose values are
1177     *               multiplied by the corresponding bitmap colors. If not null,
1178     *               there must be at least (meshWidth+1) * (meshHeight+1) +
1179     *               colorOffset values in the array.
1180     * @param colorOffset Number of color elements to skip before drawing
1181     * @param paint  May be null. The paint used to draw the bitmap
1182     */
1183    public void drawBitmapMesh(Bitmap bitmap, int meshWidth, int meshHeight,
1184                               float[] verts, int vertOffset,
1185                               int[] colors, int colorOffset, Paint paint) {
1186        if ((meshWidth | meshHeight | vertOffset | colorOffset) < 0) {
1187            throw new ArrayIndexOutOfBoundsException();
1188        }
1189        if (meshWidth == 0 || meshHeight == 0) {
1190            return;
1191        }
1192        int count = (meshWidth + 1) * (meshHeight + 1);
1193        // we mul by 2 since we need two floats per vertex
1194        checkRange(verts.length, vertOffset, count * 2);
1195        if (colors != null) {
1196            // no mul by 2, since we need only 1 color per vertex
1197            checkRange(colors.length, colorOffset, count);
1198        }
1199        nativeDrawBitmapMesh(mNativeCanvas, bitmap.ni(), meshWidth, meshHeight,
1200                             verts, vertOffset, colors, colorOffset,
1201                             paint != null ? paint.mNativePaint : 0);
1202    }
1203
1204    public enum VertexMode {
1205        TRIANGLES(0),
1206        TRIANGLE_STRIP(1),
1207        TRIANGLE_FAN(2);
1208
1209        VertexMode(int nativeInt) {
1210            this.nativeInt = nativeInt;
1211        }
1212        final int nativeInt;
1213    }
1214
1215    /**
1216     * Draw the array of vertices, interpreted as triangles (based on mode). The
1217     * verts array is required, and specifies the x,y pairs for each vertex. If
1218     * texs is non-null, then it is used to specify the coordinate in shader
1219     * coordinates to use at each vertex (the paint must have a shader in this
1220     * case). If there is no texs array, but there is a color array, then each
1221     * color is interpolated across its corresponding triangle in a gradient. If
1222     * both texs and colors arrays are present, then they behave as before, but
1223     * the resulting color at each pixels is the result of multiplying the
1224     * colors from the shader and the color-gradient together. The indices array
1225     * is optional, but if it is present, then it is used to specify the index
1226     * of each triangle, rather than just walking through the arrays in order.
1227     *
1228     * @param mode How to interpret the array of vertices
1229     * @param vertexCount The number of values in the vertices array (and
1230     *      corresponding texs and colors arrays if non-null). Each logical
1231     *      vertex is two values (x, y), vertexCount must be a multiple of 2.
1232     * @param verts Array of vertices for the mesh
1233     * @param vertOffset Number of values in the verts to skip before drawing.
1234     * @param texs May be null. If not null, specifies the coordinates to sample
1235     *      into the current shader (e.g. bitmap tile or gradient)
1236     * @param texOffset Number of values in texs to skip before drawing.
1237     * @param colors May be null. If not null, specifies a color for each
1238     *      vertex, to be interpolated across the triangle.
1239     * @param colorOffset Number of values in colors to skip before drawing.
1240     * @param indices If not null, array of indices to reference into the
1241     *      vertex (texs, colors) array.
1242     * @param indexCount number of entries in the indices array (if not null).
1243     * @param paint Specifies the shader to use if the texs array is non-null.
1244     */
1245    public void drawVertices(VertexMode mode, int vertexCount,
1246                             float[] verts, int vertOffset,
1247                             float[] texs, int texOffset,
1248                             int[] colors, int colorOffset,
1249                             short[] indices, int indexOffset,
1250                             int indexCount, Paint paint) {
1251        checkRange(verts.length, vertOffset, vertexCount);
1252        if (texs != null) {
1253            checkRange(texs.length, texOffset, vertexCount);
1254        }
1255        if (colors != null) {
1256            checkRange(colors.length, colorOffset, vertexCount / 2);
1257        }
1258        if (indices != null) {
1259            checkRange(indices.length, indexOffset, indexCount);
1260        }
1261        nativeDrawVertices(mNativeCanvas, mode.nativeInt, vertexCount, verts,
1262                           vertOffset, texs, texOffset, colors, colorOffset,
1263                          indices, indexOffset, indexCount, paint.mNativePaint);
1264    }
1265
1266    /**
1267     * Draw the text, with origin at (x,y), using the specified paint. The
1268     * origin is interpreted based on the Align setting in the paint.
1269     *
1270     * @param text  The text to be drawn
1271     * @param x     The x-coordinate of the origin of the text being drawn
1272     * @param y     The y-coordinate of the origin of the text being drawn
1273     * @param paint The paint used for the text (e.g. color, size, style)
1274     */
1275    public void drawText(char[] text, int index, int count, float x, float y,
1276                         Paint paint) {
1277        if ((index | count | (index + count) |
1278            (text.length - index - count)) < 0) {
1279            throw new IndexOutOfBoundsException();
1280        }
1281        native_drawText(mNativeCanvas, text, index, count, x, y, paint.mBidiFlags,
1282                paint.mNativePaint);
1283    }
1284
1285    /**
1286     * Draw the text, with origin at (x,y), using the specified paint. The
1287     * origin is interpreted based on the Align setting in the paint.
1288     *
1289     * @param text  The text to be drawn
1290     * @param x     The x-coordinate of the origin of the text being drawn
1291     * @param y     The y-coordinate of the origin of the text being drawn
1292     * @param paint The paint used for the text (e.g. color, size, style)
1293     */
1294    public void drawText(String text, float x, float y, Paint paint) {
1295        native_drawText(mNativeCanvas, text, 0, text.length(), x, y, paint.mBidiFlags,
1296                paint.mNativePaint);
1297    }
1298
1299    /**
1300     * Draw the text, with origin at (x,y), using the specified paint.
1301     * The origin is interpreted based on the Align setting in the paint.
1302     *
1303     * @param text  The text to be drawn
1304     * @param start The index of the first character in text to draw
1305     * @param end   (end - 1) is the index of the last character in text to draw
1306     * @param x     The x-coordinate of the origin of the text being drawn
1307     * @param y     The y-coordinate of the origin of the text being drawn
1308     * @param paint The paint used for the text (e.g. color, size, style)
1309     */
1310    public void drawText(String text, int start, int end, float x, float y,
1311                         Paint paint) {
1312        if ((start | end | (end - start) | (text.length() - end)) < 0) {
1313            throw new IndexOutOfBoundsException();
1314        }
1315        native_drawText(mNativeCanvas, text, start, end, x, y, paint.mBidiFlags,
1316                paint.mNativePaint);
1317    }
1318
1319    /**
1320     * Draw the specified range of text, specified by start/end, with its
1321     * origin at (x,y), in the specified Paint. The origin is interpreted
1322     * based on the Align setting in the Paint.
1323     *
1324     * @param text     The text to be drawn
1325     * @param start    The index of the first character in text to draw
1326     * @param end      (end - 1) is the index of the last character in text
1327     *                 to draw
1328     * @param x        The x-coordinate of origin for where to draw the text
1329     * @param y        The y-coordinate of origin for where to draw the text
1330     * @param paint The paint used for the text (e.g. color, size, style)
1331     */
1332    public void drawText(CharSequence text, int start, int end, float x,
1333                         float y, Paint paint) {
1334        if (text instanceof String || text instanceof SpannedString ||
1335            text instanceof SpannableString) {
1336            native_drawText(mNativeCanvas, text.toString(), start, end, x, y,
1337                            paint.mBidiFlags, paint.mNativePaint);
1338        } else if (text instanceof GraphicsOperations) {
1339            ((GraphicsOperations) text).drawText(this, start, end, x, y,
1340                                                     paint);
1341        } else {
1342            char[] buf = TemporaryBuffer.obtain(end - start);
1343            TextUtils.getChars(text, start, end, buf, 0);
1344            native_drawText(mNativeCanvas, buf, 0, end - start, x, y,
1345                    paint.mBidiFlags, paint.mNativePaint);
1346            TemporaryBuffer.recycle(buf);
1347        }
1348    }
1349
1350    /**
1351     * Render a run of all LTR or all RTL text, with shaping. This does not run
1352     * bidi on the provided text, but renders it as a uniform right-to-left or
1353     * left-to-right run, as indicated by dir. Alignment of the text is as
1354     * determined by the Paint's TextAlign value.
1355     *
1356     * @param text the text to render
1357     * @param index the start of the text to render
1358     * @param count the count of chars to render
1359     * @param contextIndex the start of the context for shaping.  Must be
1360     *         no greater than index.
1361     * @param contextCount the number of characters in the context for shaping.
1362     *         ContexIndex + contextCount must be no less than index
1363     *         + count.
1364     * @param x the x position at which to draw the text
1365     * @param y the y position at which to draw the text
1366     * @param dir the run direction, either {@link #DIRECTION_LTR} or
1367     *         {@link #DIRECTION_RTL}.
1368     * @param paint the paint
1369     * @hide
1370     */
1371    public void drawTextRun(char[] text, int index, int count,
1372            int contextIndex, int contextCount, float x, float y, int dir,
1373            Paint paint) {
1374
1375        if (text == null) {
1376            throw new NullPointerException("text is null");
1377        }
1378        if (paint == null) {
1379            throw new NullPointerException("paint is null");
1380        }
1381        if ((index | count | text.length - index - count) < 0) {
1382            throw new IndexOutOfBoundsException();
1383        }
1384        if (dir != DIRECTION_LTR && dir != DIRECTION_RTL) {
1385            throw new IllegalArgumentException("unknown dir: " + dir);
1386        }
1387
1388        native_drawTextRun(mNativeCanvas, text, index, count,
1389                contextIndex, contextCount, x, y, dir, paint.mNativePaint);
1390    }
1391
1392    /**
1393     * Render a run of all LTR or all RTL text, with shaping. This does not run
1394     * bidi on the provided text, but renders it as a uniform right-to-left or
1395     * left-to-right run, as indicated by dir. Alignment of the text is as
1396     * determined by the Paint's TextAlign value.
1397     *
1398     * @param text the text to render
1399     * @param start the start of the text to render. Data before this position
1400     *            can be used for shaping context.
1401     * @param end the end of the text to render. Data at or after this
1402     *            position can be used for shaping context.
1403     * @param x the x position at which to draw the text
1404     * @param y the y position at which to draw the text
1405     * @param dir the run direction, either 0 for LTR or 1 for RTL.
1406     * @param paint the paint
1407     * @hide
1408     */
1409    public void drawTextRun(CharSequence text, int start, int end,
1410            int contextStart, int contextEnd, float x, float y, int dir,
1411            Paint paint) {
1412
1413        if (text == null) {
1414            throw new NullPointerException("text is null");
1415        }
1416        if (paint == null) {
1417            throw new NullPointerException("paint is null");
1418        }
1419        if ((start | end | end - start | text.length() - end) < 0) {
1420            throw new IndexOutOfBoundsException();
1421        }
1422
1423        int flags = dir == 0 ? 0 : 1;
1424
1425        if (text instanceof String || text instanceof SpannedString ||
1426                text instanceof SpannableString) {
1427            native_drawTextRun(mNativeCanvas, text.toString(), start, end,
1428                    contextStart, contextEnd, x, y, flags, paint.mNativePaint);
1429        } else if (text instanceof GraphicsOperations) {
1430            ((GraphicsOperations) text).drawTextRun(this, start, end,
1431                    contextStart, contextEnd, x, y, flags, paint);
1432        } else {
1433            int contextLen = contextEnd - contextStart;
1434            int len = end - start;
1435            char[] buf = TemporaryBuffer.obtain(contextLen);
1436            TextUtils.getChars(text, contextStart, contextEnd, buf, 0);
1437            native_drawTextRun(mNativeCanvas, buf, start - contextStart, len,
1438                    0, contextLen, x, y, flags, paint.mNativePaint);
1439            TemporaryBuffer.recycle(buf);
1440        }
1441    }
1442
1443    /**
1444     * Draw the text in the array, with each character's origin specified by
1445     * the pos array.
1446     *
1447     * @param text     The text to be drawn
1448     * @param index    The index of the first character to draw
1449     * @param count    The number of characters to draw, starting from index.
1450     * @param pos      Array of [x,y] positions, used to position each
1451     *                 character
1452     * @param paint    The paint used for the text (e.g. color, size, style)
1453     */
1454    public void drawPosText(char[] text, int index, int count, float[] pos,
1455                            Paint paint) {
1456        if (index < 0 || index + count > text.length || count*2 > pos.length) {
1457            throw new IndexOutOfBoundsException();
1458        }
1459        native_drawPosText(mNativeCanvas, text, index, count, pos,
1460                           paint.mNativePaint);
1461    }
1462
1463    /**
1464     * Draw the text in the array, with each character's origin specified by
1465     * the pos array.
1466     *
1467     * @param text  The text to be drawn
1468     * @param pos   Array of [x,y] positions, used to position each character
1469     * @param paint The paint used for the text (e.g. color, size, style)
1470     */
1471    public void drawPosText(String text, float[] pos, Paint paint) {
1472        if (text.length()*2 > pos.length) {
1473            throw new ArrayIndexOutOfBoundsException();
1474        }
1475        native_drawPosText(mNativeCanvas, text, pos, paint.mNativePaint);
1476    }
1477
1478    /**
1479     * Draw the text, with origin at (x,y), using the specified paint, along
1480     * the specified path. The paint's Align setting determins where along the
1481     * path to start the text.
1482     *
1483     * @param text     The text to be drawn
1484     * @param path     The path the text should follow for its baseline
1485     * @param hOffset  The distance along the path to add to the text's
1486     *                 starting position
1487     * @param vOffset  The distance above(-) or below(+) the path to position
1488     *                 the text
1489     * @param paint    The paint used for the text (e.g. color, size, style)
1490     */
1491    public void drawTextOnPath(char[] text, int index, int count, Path path,
1492                               float hOffset, float vOffset, Paint paint) {
1493        if (index < 0 || index + count > text.length) {
1494            throw new ArrayIndexOutOfBoundsException();
1495        }
1496        native_drawTextOnPath(mNativeCanvas, text, index, count,
1497                              path.ni(), hOffset, vOffset,
1498                              paint.mNativePaint);
1499    }
1500
1501    /**
1502     * Draw the text, with origin at (x,y), using the specified paint, along
1503     * the specified path. The paint's Align setting determins where along the
1504     * path to start the text.
1505     *
1506     * @param text     The text to be drawn
1507     * @param path     The path the text should follow for its baseline
1508     * @param hOffset  The distance along the path to add to the text's
1509     *                 starting position
1510     * @param vOffset  The distance above(-) or below(+) the path to position
1511     *                 the text
1512     * @param paint    The paint used for the text (e.g. color, size, style)
1513     */
1514    public void drawTextOnPath(String text, Path path, float hOffset,
1515                               float vOffset, Paint paint) {
1516        if (text.length() > 0) {
1517            native_drawTextOnPath(mNativeCanvas, text, path.ni(),
1518                                  hOffset, vOffset, paint.mNativePaint);
1519        }
1520    }
1521
1522    /**
1523     * Save the canvas state, draw the picture, and restore the canvas state.
1524     * This differs from picture.draw(canvas), which does not perform any
1525     * save/restore.
1526     *
1527     * @param picture  The picture to be drawn
1528     */
1529    public void drawPicture(Picture picture) {
1530        picture.endRecording();
1531        native_drawPicture(mNativeCanvas, picture.ni());
1532    }
1533
1534    /**
1535     * Draw the picture, stretched to fit into the dst rectangle.
1536     */
1537    public void drawPicture(Picture picture, RectF dst) {
1538        save();
1539        translate(dst.left, dst.top);
1540        if (picture.getWidth() > 0 && picture.getHeight() > 0) {
1541            scale(dst.width() / picture.getWidth(),
1542                  dst.height() / picture.getHeight());
1543        }
1544        drawPicture(picture);
1545        restore();
1546    }
1547
1548    /**
1549     * Draw the picture, stretched to fit into the dst rectangle.
1550     */
1551    public void drawPicture(Picture picture, Rect dst) {
1552        save();
1553        translate(dst.left, dst.top);
1554        if (picture.getWidth() > 0 && picture.getHeight() > 0) {
1555            scale((float)dst.width() / picture.getWidth(),
1556                  (float)dst.height() / picture.getHeight());
1557        }
1558        drawPicture(picture);
1559        restore();
1560    }
1561
1562    protected void finalize() throws Throwable {
1563        super.finalize();
1564        // If the constructor threw an exception before setting mNativeCanvas, the native finalizer
1565        // must not be invoked.
1566        if (mNativeCanvas != 0) {
1567            finalizer(mNativeCanvas);
1568        }
1569    }
1570
1571    /**
1572     * Free up as much memory as possible from private caches (e.g. fonts,
1573     * images)
1574     *
1575     * @hide - for now
1576     */
1577    public static native void freeCaches();
1578
1579    private static native int initRaster(int nativeBitmapOrZero);
1580    private static native int initGL();
1581    private static native void native_setBitmap(int nativeCanvas, int bitmap);
1582    private static native void nativeSetViewport(int nCanvas, int w, int h);
1583    private static native int native_saveLayer(int nativeCanvas, RectF bounds,
1584                                               int paint, int layerFlags);
1585    private static native int native_saveLayer(int nativeCanvas, float l,
1586                                               float t, float r, float b,
1587                                               int paint, int layerFlags);
1588    private static native int native_saveLayerAlpha(int nativeCanvas,
1589                                                    RectF bounds, int alpha,
1590                                                    int layerFlags);
1591    private static native int native_saveLayerAlpha(int nativeCanvas, float l,
1592                                                    float t, float r, float b,
1593                                                    int alpha, int layerFlags);
1594
1595    private static native void native_concat(int nCanvas, int nMatrix);
1596    private static native void native_setMatrix(int nCanvas, int nMatrix);
1597    private static native boolean native_clipRect(int nCanvas,
1598                                                  float left, float top,
1599                                                  float right, float bottom,
1600                                                  int regionOp);
1601    private static native boolean native_clipPath(int nativeCanvas,
1602                                                  int nativePath,
1603                                                  int regionOp);
1604    private static native boolean native_clipRegion(int nativeCanvas,
1605                                                    int nativeRegion,
1606                                                    int regionOp);
1607    private static native void nativeSetDrawFilter(int nativeCanvas,
1608                                                   int nativeFilter);
1609    private static native boolean native_getClipBounds(int nativeCanvas,
1610                                                       Rect bounds);
1611    private static native void native_getCTM(int canvas, int matrix);
1612    private static native boolean native_quickReject(int nativeCanvas,
1613                                                     RectF rect,
1614                                                     int native_edgeType);
1615    private static native boolean native_quickReject(int nativeCanvas,
1616                                                     int path,
1617                                                     int native_edgeType);
1618    private static native boolean native_quickReject(int nativeCanvas,
1619                                                     float left, float top,
1620                                                     float right, float bottom,
1621                                                     int native_edgeType);
1622    private static native void native_drawRGB(int nativeCanvas, int r, int g,
1623                                              int b);
1624    private static native void native_drawARGB(int nativeCanvas, int a, int r,
1625                                               int g, int b);
1626    private static native void native_drawColor(int nativeCanvas, int color);
1627    private static native void native_drawColor(int nativeCanvas, int color,
1628                                                int mode);
1629    private static native void native_drawPaint(int nativeCanvas, int paint);
1630    private static native void native_drawLine(int nativeCanvas, float startX,
1631                                               float startY, float stopX,
1632                                               float stopY, int paint);
1633    private static native void native_drawRect(int nativeCanvas, RectF rect,
1634                                               int paint);
1635    private static native void native_drawRect(int nativeCanvas, float left,
1636                                               float top, float right,
1637                                               float bottom, int paint);
1638    private static native void native_drawOval(int nativeCanvas, RectF oval,
1639                                               int paint);
1640    private static native void native_drawCircle(int nativeCanvas, float cx,
1641                                                 float cy, float radius,
1642                                                 int paint);
1643    private static native void native_drawArc(int nativeCanvas, RectF oval,
1644                                              float startAngle, float sweep,
1645                                              boolean useCenter, int paint);
1646    private static native void native_drawRoundRect(int nativeCanvas,
1647                                                    RectF rect, float rx,
1648                                                    float ry, int paint);
1649    private static native void native_drawPath(int nativeCanvas, int path,
1650                                               int paint);
1651    private native void native_drawBitmap(int nativeCanvas, int bitmap,
1652                                                 float left, float top,
1653                                                 int nativePaintOrZero,
1654                                                 int canvasDensity,
1655                                                 int screenDensity,
1656                                                 int bitmapDensity);
1657    private native void native_drawBitmap(int nativeCanvas, int bitmap,
1658                                                 Rect src, RectF dst,
1659                                                 int nativePaintOrZero,
1660                                                 int screenDensity,
1661                                                 int bitmapDensity);
1662    private static native void native_drawBitmap(int nativeCanvas, int bitmap,
1663                                                 Rect src, Rect dst,
1664                                                 int nativePaintOrZero,
1665                                                 int screenDensity,
1666                                                 int bitmapDensity);
1667    private static native void native_drawBitmap(int nativeCanvas, int[] colors,
1668                                                int offset, int stride, float x,
1669                                                 float y, int width, int height,
1670                                                 boolean hasAlpha,
1671                                                 int nativePaintOrZero);
1672    private static native void nativeDrawBitmapMatrix(int nCanvas, int nBitmap,
1673                                                      int nMatrix, int nPaint);
1674    private static native void nativeDrawBitmapMesh(int nCanvas, int nBitmap,
1675                                                    int meshWidth, int meshHeight,
1676                                                    float[] verts, int vertOffset,
1677                                                    int[] colors, int colorOffset, int nPaint);
1678    private static native void nativeDrawVertices(int nCanvas, int mode, int n,
1679                   float[] verts, int vertOffset, float[] texs, int texOffset,
1680                   int[] colors, int colorOffset, short[] indices,
1681                   int indexOffset, int indexCount, int nPaint);
1682
1683    private static native void native_drawText(int nativeCanvas, char[] text,
1684                                               int index, int count, float x,
1685                                               float y, int flags, int paint);
1686    private static native void native_drawText(int nativeCanvas, String text,
1687                                               int start, int end, float x,
1688                                               float y, int flags, int paint);
1689
1690    private static native void native_drawTextRun(int nativeCanvas, String text,
1691            int start, int end, int contextStart, int contextEnd,
1692            float x, float y, int flags, int paint);
1693
1694    private static native void native_drawTextRun(int nativeCanvas, char[] text,
1695            int start, int count, int contextStart, int contextCount,
1696            float x, float y, int flags, int paint);
1697
1698    private static native void native_drawPosText(int nativeCanvas,
1699                                                  char[] text, int index,
1700                                                  int count, float[] pos,
1701                                                  int paint);
1702    private static native void native_drawPosText(int nativeCanvas,
1703                                                  String text, float[] pos,
1704                                                  int paint);
1705    private static native void native_drawTextOnPath(int nativeCanvas,
1706                                                     char[] text, int index,
1707                                                     int count, int path,
1708                                                     float hOffset,
1709                                                     float vOffset, int paint);
1710    private static native void native_drawTextOnPath(int nativeCanvas,
1711                                                     String text, int path,
1712                                                     float hOffset,
1713                                                     float vOffset, int paint);
1714    private static native void native_drawPicture(int nativeCanvas,
1715                                                  int nativePicture);
1716    private static native void finalizer(int nativeCanvas);
1717}
1718