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