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