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