Canvas.java revision cd23df6a08cf7a9bdee11e703f40bca5904d779d
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 long 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 long mNativeCanvas;
88
89        public CanvasFinalizer(long 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        throwIfCannotDraw(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(long 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(long nativeCanvas, boolean copyState) {
161        final long 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 long 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            throwIfCannotDraw(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        long 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    /**
1080     * @hide
1081     */
1082    protected static void throwIfCannotDraw(Bitmap bitmap) {
1083        if (bitmap.isRecycled()) {
1084            throw new RuntimeException("Canvas: trying to use a recycled bitmap " + bitmap);
1085        }
1086        if (!bitmap.isPremultiplied() && bitmap.getConfig() == Bitmap.Config.ARGB_8888 &&
1087                bitmap.hasAlpha()) {
1088            throw new RuntimeException("Canvas: trying to use a non-premultiplied bitmap "
1089                    + bitmap);
1090        }
1091    }
1092
1093    /**
1094     * Draws the specified bitmap as an N-patch (most often, a 9-patches.)
1095     *
1096     * @param patch The ninepatch object to render
1097     * @param dst The destination rectangle.
1098     * @param paint The paint to draw the bitmap with. may be null
1099     *
1100     * @hide
1101     */
1102    public void drawPatch(NinePatch patch, Rect dst, Paint paint) {
1103        patch.drawSoftware(this, dst, paint);
1104    }
1105
1106    /**
1107     * Draws the specified bitmap as an N-patch (most often, a 9-patches.)
1108     *
1109     * @param patch The ninepatch object to render
1110     * @param dst The destination rectangle.
1111     * @param paint The paint to draw the bitmap with. may be null
1112     *
1113     * @hide
1114     */
1115    public void drawPatch(NinePatch patch, RectF dst, Paint paint) {
1116        patch.drawSoftware(this, dst, paint);
1117    }
1118
1119    /**
1120     * Draw the specified bitmap, with its top/left corner at (x,y), using
1121     * the specified paint, transformed by the current matrix.
1122     *
1123     * <p>Note: if the paint contains a maskfilter that generates a mask which
1124     * extends beyond the bitmap's original width/height (e.g. BlurMaskFilter),
1125     * then the bitmap will be drawn as if it were in a Shader with CLAMP mode.
1126     * Thus the color outside of the original width/height will be the edge
1127     * color replicated.
1128     *
1129     * <p>If the bitmap and canvas have different densities, this function
1130     * will take care of automatically scaling the bitmap to draw at the
1131     * same density as the canvas.
1132     *
1133     * @param bitmap The bitmap to be drawn
1134     * @param left   The position of the left side of the bitmap being drawn
1135     * @param top    The position of the top side of the bitmap being drawn
1136     * @param paint  The paint used to draw the bitmap (may be null)
1137     */
1138    public void drawBitmap(Bitmap bitmap, float left, float top, Paint paint) {
1139        throwIfCannotDraw(bitmap);
1140        native_drawBitmap(mNativeCanvas, bitmap.ni(), left, top,
1141                paint != null ? paint.mNativePaint : 0, mDensity, mScreenDensity, bitmap.mDensity);
1142    }
1143
1144    /**
1145     * Draw the specified bitmap, scaling/translating automatically to fill
1146     * the destination rectangle. If the source rectangle is not null, it
1147     * specifies the subset of the bitmap to draw.
1148     *
1149     * <p>Note: if the paint contains a maskfilter that generates a mask which
1150     * extends beyond the bitmap's original width/height (e.g. BlurMaskFilter),
1151     * then the bitmap will be drawn as if it were in a Shader with CLAMP mode.
1152     * Thus the color outside of the original width/height will be the edge
1153     * color replicated.
1154     *
1155     * <p>This function <em>ignores the density associated with the bitmap</em>.
1156     * This is because the source and destination rectangle coordinate
1157     * spaces are in their respective densities, so must already have the
1158     * appropriate scaling factor applied.
1159     *
1160     * @param bitmap The bitmap to be drawn
1161     * @param src    May be null. The subset of the bitmap to be drawn
1162     * @param dst    The rectangle that the bitmap will be scaled/translated
1163     *               to fit into
1164     * @param paint  May be null. The paint used to draw the bitmap
1165     */
1166    public void drawBitmap(Bitmap bitmap, Rect src, RectF dst, Paint paint) {
1167        if (dst == null) {
1168            throw new NullPointerException();
1169        }
1170        throwIfCannotDraw(bitmap);
1171        native_drawBitmap(mNativeCanvas, bitmap.ni(), src, dst,
1172                          paint != null ? paint.mNativePaint : 0, mScreenDensity, bitmap.mDensity);
1173    }
1174
1175    /**
1176     * Draw the specified bitmap, scaling/translating automatically to fill
1177     * the destination rectangle. If the source rectangle is not null, it
1178     * specifies the subset of the bitmap to draw.
1179     *
1180     * <p>Note: if the paint contains a maskfilter that generates a mask which
1181     * extends beyond the bitmap's original width/height (e.g. BlurMaskFilter),
1182     * then the bitmap will be drawn as if it were in a Shader with CLAMP mode.
1183     * Thus the color outside of the original width/height will be the edge
1184     * color replicated.
1185     *
1186     * <p>This function <em>ignores the density associated with the bitmap</em>.
1187     * This is because the source and destination rectangle coordinate
1188     * spaces are in their respective densities, so must already have the
1189     * appropriate scaling factor applied.
1190     *
1191     * @param bitmap The bitmap to be drawn
1192     * @param src    May be null. The subset of the bitmap to be drawn
1193     * @param dst    The rectangle that the bitmap will be scaled/translated
1194     *               to fit into
1195     * @param paint  May be null. The paint used to draw the bitmap
1196     */
1197    public void drawBitmap(Bitmap bitmap, Rect src, Rect dst, Paint paint) {
1198        if (dst == null) {
1199            throw new NullPointerException();
1200        }
1201        throwIfCannotDraw(bitmap);
1202        native_drawBitmap(mNativeCanvas, bitmap.ni(), src, dst,
1203                paint != null ? paint.mNativePaint : 0, mScreenDensity, bitmap.mDensity);
1204    }
1205
1206    /**
1207     * Treat the specified array of colors as a bitmap, and draw it. This gives
1208     * the same result as first creating a bitmap from the array, and then
1209     * drawing it, but this method avoids explicitly creating a bitmap object
1210     * which can be more efficient if the colors are changing often.
1211     *
1212     * @param colors Array of colors representing the pixels of the bitmap
1213     * @param offset Offset into the array of colors for the first pixel
1214     * @param stride The number of colors in the array between rows (must be
1215     *               >= width or <= -width).
1216     * @param x The X coordinate for where to draw the bitmap
1217     * @param y The Y coordinate for where to draw the bitmap
1218     * @param width The width of the bitmap
1219     * @param height The height of the bitmap
1220     * @param hasAlpha True if the alpha channel of the colors contains valid
1221     *                 values. If false, the alpha byte is ignored (assumed to
1222     *                 be 0xFF for every pixel).
1223     * @param paint  May be null. The paint used to draw the bitmap
1224     *
1225     * @deprecated Usage with a {@link #isHardwareAccelerated() hardware accelerated} canvas
1226     * requires an internal copy of color buffer contents every time this method is called. Using a
1227     * Bitmap avoids this copy, and allows the application to more explicitly control the lifetime
1228     * and copies of pixel data.
1229     */
1230    @Deprecated
1231    public void drawBitmap(int[] colors, int offset, int stride, float x, float y,
1232            int width, int height, boolean hasAlpha, Paint paint) {
1233        // check for valid input
1234        if (width < 0) {
1235            throw new IllegalArgumentException("width must be >= 0");
1236        }
1237        if (height < 0) {
1238            throw new IllegalArgumentException("height must be >= 0");
1239        }
1240        if (Math.abs(stride) < width) {
1241            throw new IllegalArgumentException("abs(stride) must be >= width");
1242        }
1243        int lastScanline = offset + (height - 1) * stride;
1244        int length = colors.length;
1245        if (offset < 0 || (offset + width > length) || lastScanline < 0
1246                || (lastScanline + width > length)) {
1247            throw new ArrayIndexOutOfBoundsException();
1248        }
1249        // quick escape if there's nothing to draw
1250        if (width == 0 || height == 0) {
1251            return;
1252        }
1253        // punch down to native for the actual draw
1254        native_drawBitmap(mNativeCanvas, colors, offset, stride, x, y, width, height, hasAlpha,
1255                paint != null ? paint.mNativePaint : 0);
1256    }
1257
1258    /**
1259     * Legacy version of drawBitmap(int[] colors, ...) that took ints for x,y
1260     *
1261     * @deprecated Usage with a {@link #isHardwareAccelerated() hardware accelerated} canvas
1262     * requires an internal copy of color buffer contents every time this method is called. Using a
1263     * Bitmap avoids this copy, and allows the application to more explicitly control the lifetime
1264     * and copies of pixel data.
1265     */
1266    @Deprecated
1267    public void drawBitmap(int[] colors, int offset, int stride, int x, int y,
1268            int width, int height, boolean hasAlpha, Paint paint) {
1269        // call through to the common float version
1270        drawBitmap(colors, offset, stride, (float)x, (float)y, width, height,
1271                   hasAlpha, paint);
1272    }
1273
1274    /**
1275     * Draw the bitmap using the specified matrix.
1276     *
1277     * @param bitmap The bitmap to draw
1278     * @param matrix The matrix used to transform the bitmap when it is drawn
1279     * @param paint  May be null. The paint used to draw the bitmap
1280     */
1281    public void drawBitmap(Bitmap bitmap, Matrix matrix, Paint paint) {
1282        nativeDrawBitmapMatrix(mNativeCanvas, bitmap.ni(), matrix.ni(),
1283                paint != null ? paint.mNativePaint : 0);
1284    }
1285
1286    /**
1287     * @hide
1288     */
1289    protected static void checkRange(int length, int offset, int count) {
1290        if ((offset | count) < 0 || offset + count > length) {
1291            throw new ArrayIndexOutOfBoundsException();
1292        }
1293    }
1294
1295    /**
1296     * Draw the bitmap through the mesh, where mesh vertices are evenly
1297     * distributed across the bitmap. There are meshWidth+1 vertices across, and
1298     * meshHeight+1 vertices down. The verts array is accessed in row-major
1299     * order, so that the first meshWidth+1 vertices are distributed across the
1300     * top of the bitmap from left to right. A more general version of this
1301     * method is drawVertices().
1302     *
1303     * @param bitmap The bitmap to draw using the mesh
1304     * @param meshWidth The number of columns in the mesh. Nothing is drawn if
1305     *                  this is 0
1306     * @param meshHeight The number of rows in the mesh. Nothing is drawn if
1307     *                   this is 0
1308     * @param verts Array of x,y pairs, specifying where the mesh should be
1309     *              drawn. There must be at least
1310     *              (meshWidth+1) * (meshHeight+1) * 2 + vertOffset values
1311     *              in the array
1312     * @param vertOffset Number of verts elements to skip before drawing
1313     * @param colors May be null. Specifies a color at each vertex, which is
1314     *               interpolated across the cell, and whose values are
1315     *               multiplied by the corresponding bitmap colors. If not null,
1316     *               there must be at least (meshWidth+1) * (meshHeight+1) +
1317     *               colorOffset values in the array.
1318     * @param colorOffset Number of color elements to skip before drawing
1319     * @param paint  May be null. The paint used to draw the bitmap
1320     */
1321    public void drawBitmapMesh(Bitmap bitmap, int meshWidth, int meshHeight,
1322            float[] verts, int vertOffset, int[] colors, int colorOffset, Paint paint) {
1323        if ((meshWidth | meshHeight | vertOffset | colorOffset) < 0) {
1324            throw new ArrayIndexOutOfBoundsException();
1325        }
1326        if (meshWidth == 0 || meshHeight == 0) {
1327            return;
1328        }
1329        int count = (meshWidth + 1) * (meshHeight + 1);
1330        // we mul by 2 since we need two floats per vertex
1331        checkRange(verts.length, vertOffset, count * 2);
1332        if (colors != null) {
1333            // no mul by 2, since we need only 1 color per vertex
1334            checkRange(colors.length, colorOffset, count);
1335        }
1336        nativeDrawBitmapMesh(mNativeCanvas, bitmap.ni(), meshWidth, meshHeight,
1337                verts, vertOffset, colors, colorOffset,
1338                paint != null ? paint.mNativePaint : 0);
1339    }
1340
1341    public enum VertexMode {
1342        TRIANGLES(0),
1343        TRIANGLE_STRIP(1),
1344        TRIANGLE_FAN(2);
1345
1346        VertexMode(int nativeInt) {
1347            this.nativeInt = nativeInt;
1348        }
1349
1350        /**
1351         * @hide
1352         */
1353        public final int nativeInt;
1354    }
1355
1356    /**
1357     * Draw the array of vertices, interpreted as triangles (based on mode). The
1358     * verts array is required, and specifies the x,y pairs for each vertex. If
1359     * texs is non-null, then it is used to specify the coordinate in shader
1360     * coordinates to use at each vertex (the paint must have a shader in this
1361     * case). If there is no texs array, but there is a color array, then each
1362     * color is interpolated across its corresponding triangle in a gradient. If
1363     * both texs and colors arrays are present, then they behave as before, but
1364     * the resulting color at each pixels is the result of multiplying the
1365     * colors from the shader and the color-gradient together. The indices array
1366     * is optional, but if it is present, then it is used to specify the index
1367     * of each triangle, rather than just walking through the arrays in order.
1368     *
1369     * @param mode How to interpret the array of vertices
1370     * @param vertexCount The number of values in the vertices array (and
1371     *      corresponding texs and colors arrays if non-null). Each logical
1372     *      vertex is two values (x, y), vertexCount must be a multiple of 2.
1373     * @param verts Array of vertices for the mesh
1374     * @param vertOffset Number of values in the verts to skip before drawing.
1375     * @param texs May be null. If not null, specifies the coordinates to sample
1376     *      into the current shader (e.g. bitmap tile or gradient)
1377     * @param texOffset Number of values in texs to skip before drawing.
1378     * @param colors May be null. If not null, specifies a color for each
1379     *      vertex, to be interpolated across the triangle.
1380     * @param colorOffset Number of values in colors to skip before drawing.
1381     * @param indices If not null, array of indices to reference into the
1382     *      vertex (texs, colors) array.
1383     * @param indexCount number of entries in the indices array (if not null).
1384     * @param paint Specifies the shader to use if the texs array is non-null.
1385     */
1386    public void drawVertices(VertexMode mode, int vertexCount, float[] verts, int vertOffset,
1387            float[] texs, int texOffset, int[] colors, int colorOffset,
1388            short[] indices, int indexOffset, int indexCount, Paint paint) {
1389        checkRange(verts.length, vertOffset, vertexCount);
1390        if (texs != null) {
1391            checkRange(texs.length, texOffset, vertexCount);
1392        }
1393        if (colors != null) {
1394            checkRange(colors.length, colorOffset, vertexCount / 2);
1395        }
1396        if (indices != null) {
1397            checkRange(indices.length, indexOffset, indexCount);
1398        }
1399        nativeDrawVertices(mNativeCanvas, mode.nativeInt, vertexCount, verts,
1400                vertOffset, texs, texOffset, colors, colorOffset,
1401                indices, indexOffset, indexCount, paint.mNativePaint);
1402    }
1403
1404    /**
1405     * Draw the text, with origin at (x,y), using the specified paint. The
1406     * origin is interpreted based on the Align setting in the paint.
1407     *
1408     * @param text  The text to be drawn
1409     * @param x     The x-coordinate of the origin of the text being drawn
1410     * @param y     The y-coordinate of the origin of the text being drawn
1411     * @param paint The paint used for the text (e.g. color, size, style)
1412     */
1413    public void drawText(char[] text, int index, int count, float x, float y, Paint paint) {
1414        if ((index | count | (index + count) |
1415            (text.length - index - count)) < 0) {
1416            throw new IndexOutOfBoundsException();
1417        }
1418        native_drawText(mNativeCanvas, text, index, count, x, y, paint.mBidiFlags,
1419                paint.mNativePaint, paint.mNativeTypeface);
1420    }
1421
1422    /**
1423     * Draw the text, with origin at (x,y), using the specified paint. The
1424     * origin is interpreted based on the Align setting in the paint.
1425     *
1426     * @param text  The text to be drawn
1427     * @param x     The x-coordinate of the origin of the text being drawn
1428     * @param y     The y-coordinate of the origin of the text being drawn
1429     * @param paint The paint used for the text (e.g. color, size, style)
1430     */
1431    public void drawText(String text, float x, float y, Paint paint) {
1432        native_drawText(mNativeCanvas, text, 0, text.length(), x, y, paint.mBidiFlags,
1433                paint.mNativePaint, paint.mNativeTypeface);
1434    }
1435
1436    /**
1437     * Draw the text, with origin at (x,y), using the specified paint.
1438     * The origin is interpreted based on the Align setting in the paint.
1439     *
1440     * @param text  The text to be drawn
1441     * @param start The index of the first character in text to draw
1442     * @param end   (end - 1) is the index of the last character in text to draw
1443     * @param x     The x-coordinate of the origin of the text being drawn
1444     * @param y     The y-coordinate of the origin of the text being drawn
1445     * @param paint The paint used for the text (e.g. color, size, style)
1446     */
1447    public void drawText(String text, int start, int end, float x, float y, Paint paint) {
1448        if ((start | end | (end - start) | (text.length() - end)) < 0) {
1449            throw new IndexOutOfBoundsException();
1450        }
1451        native_drawText(mNativeCanvas, text, start, end, x, y, paint.mBidiFlags,
1452                paint.mNativePaint, paint.mNativeTypeface);
1453    }
1454
1455    /**
1456     * Draw the specified range of text, specified by start/end, with its
1457     * origin at (x,y), in the specified Paint. The origin is interpreted
1458     * based on the Align setting in the Paint.
1459     *
1460     * @param text     The text to be drawn
1461     * @param start    The index of the first character in text to draw
1462     * @param end      (end - 1) is the index of the last character in text
1463     *                 to draw
1464     * @param x        The x-coordinate of origin for where to draw the text
1465     * @param y        The y-coordinate of origin for where to draw the text
1466     * @param paint The paint used for the text (e.g. color, size, style)
1467     */
1468    public void drawText(CharSequence text, int start, int end, float x, float y, Paint paint) {
1469        if (text instanceof String || text instanceof SpannedString ||
1470            text instanceof SpannableString) {
1471            native_drawText(mNativeCanvas, text.toString(), start, end, x, y,
1472                    paint.mBidiFlags, paint.mNativePaint, paint.mNativeTypeface);
1473        } else if (text instanceof GraphicsOperations) {
1474            ((GraphicsOperations) text).drawText(this, start, end, x, y,
1475                    paint);
1476        } else {
1477            char[] buf = TemporaryBuffer.obtain(end - start);
1478            TextUtils.getChars(text, start, end, buf, 0);
1479            native_drawText(mNativeCanvas, buf, 0, end - start, x, y,
1480                    paint.mBidiFlags, paint.mNativePaint, paint.mNativeTypeface);
1481            TemporaryBuffer.recycle(buf);
1482        }
1483    }
1484
1485    /**
1486     * Render a run of all LTR or all RTL text, with shaping. This does not run
1487     * bidi on the provided text, but renders it as a uniform right-to-left or
1488     * left-to-right run, as indicated by dir. Alignment of the text is as
1489     * determined by the Paint's TextAlign value.
1490     *
1491     * @param text the text to render
1492     * @param index the start of the text to render
1493     * @param count the count of chars to render
1494     * @param contextIndex the start of the context for shaping.  Must be
1495     *         no greater than index.
1496     * @param contextCount the number of characters in the context for shaping.
1497     *         ContexIndex + contextCount must be no less than index
1498     *         + count.
1499     * @param x the x position at which to draw the text
1500     * @param y the y position at which to draw the text
1501     * @param dir the run direction, either {@link #DIRECTION_LTR} or
1502     *         {@link #DIRECTION_RTL}.
1503     * @param paint the paint
1504     * @hide
1505     */
1506    public void drawTextRun(char[] text, int index, int count, int contextIndex, int contextCount,
1507            float x, float y, int dir, Paint paint) {
1508
1509        if (text == null) {
1510            throw new NullPointerException("text is null");
1511        }
1512        if (paint == null) {
1513            throw new NullPointerException("paint is null");
1514        }
1515        if ((index | count | text.length - index - count) < 0) {
1516            throw new IndexOutOfBoundsException();
1517        }
1518        if (dir != DIRECTION_LTR && dir != DIRECTION_RTL) {
1519            throw new IllegalArgumentException("unknown dir: " + dir);
1520        }
1521
1522        native_drawTextRun(mNativeCanvas, text, index, count,
1523                contextIndex, contextCount, x, y, dir, paint.mNativePaint, paint.mNativeTypeface);
1524    }
1525
1526    /**
1527     * Render a run of all LTR or all RTL text, with shaping. This does not run
1528     * bidi on the provided text, but renders it as a uniform right-to-left or
1529     * left-to-right run, as indicated by dir. Alignment of the text is as
1530     * determined by the Paint's TextAlign value.
1531     *
1532     * @param text the text to render
1533     * @param start the start of the text to render. Data before this position
1534     *            can be used for shaping context.
1535     * @param end the end of the text to render. Data at or after this
1536     *            position can be used for shaping context.
1537     * @param x the x position at which to draw the text
1538     * @param y the y position at which to draw the text
1539     * @param dir the run direction, either 0 for LTR or 1 for RTL.
1540     * @param paint the paint
1541     * @hide
1542     */
1543    public void drawTextRun(CharSequence text, int start, int end, int contextStart, int contextEnd,
1544            float x, float y, int dir, Paint paint) {
1545
1546        if (text == null) {
1547            throw new NullPointerException("text is null");
1548        }
1549        if (paint == null) {
1550            throw new NullPointerException("paint is null");
1551        }
1552        if ((start | end | end - start | text.length() - end) < 0) {
1553            throw new IndexOutOfBoundsException();
1554        }
1555
1556        int flags = dir == 0 ? 0 : 1;
1557
1558        if (text instanceof String || text instanceof SpannedString ||
1559                text instanceof SpannableString) {
1560            native_drawTextRun(mNativeCanvas, text.toString(), start, end,
1561                    contextStart, contextEnd, x, y, flags, paint.mNativePaint, paint.mNativeTypeface);
1562        } else if (text instanceof GraphicsOperations) {
1563            ((GraphicsOperations) text).drawTextRun(this, start, end,
1564                    contextStart, contextEnd, x, y, flags, paint);
1565        } else {
1566            int contextLen = contextEnd - contextStart;
1567            int len = end - start;
1568            char[] buf = TemporaryBuffer.obtain(contextLen);
1569            TextUtils.getChars(text, contextStart, contextEnd, buf, 0);
1570            native_drawTextRun(mNativeCanvas, buf, start - contextStart, len,
1571                    0, contextLen, x, y, flags, paint.mNativePaint, paint.mNativeTypeface);
1572            TemporaryBuffer.recycle(buf);
1573        }
1574    }
1575
1576    /**
1577     * Draw the text in the array, with each character's origin specified by
1578     * the pos array.
1579     *
1580     * This method does not support glyph composition and decomposition and
1581     * should therefore not be used to render complex scripts.
1582     *
1583     * @param text     The text to be drawn
1584     * @param index    The index of the first character to draw
1585     * @param count    The number of characters to draw, starting from index.
1586     * @param pos      Array of [x,y] positions, used to position each
1587     *                 character
1588     * @param paint    The paint used for the text (e.g. color, size, style)
1589     */
1590    @Deprecated
1591    public void drawPosText(char[] text, int index, int count, float[] pos, Paint paint) {
1592        if (index < 0 || index + count > text.length || count*2 > pos.length) {
1593            throw new IndexOutOfBoundsException();
1594        }
1595        native_drawPosText(mNativeCanvas, text, index, count, pos,
1596                paint.mNativePaint);
1597    }
1598
1599    /**
1600     * Draw the text in the array, with each character's origin specified by
1601     * the pos array.
1602     *
1603     * This method does not support glyph composition and decomposition and
1604     * should therefore not be used to render complex scripts.
1605     *
1606     * @param text  The text to be drawn
1607     * @param pos   Array of [x,y] positions, used to position each character
1608     * @param paint The paint used for the text (e.g. color, size, style)
1609     */
1610    @Deprecated
1611    public void drawPosText(String text, float[] pos, Paint paint) {
1612        if (text.length()*2 > pos.length) {
1613            throw new ArrayIndexOutOfBoundsException();
1614        }
1615        native_drawPosText(mNativeCanvas, text, pos, paint.mNativePaint);
1616    }
1617
1618    /**
1619     * Draw the text, with origin at (x,y), using the specified paint, along
1620     * the specified path. The paint's Align setting determins where along the
1621     * path to start the text.
1622     *
1623     * @param text     The text to be drawn
1624     * @param path     The path the text should follow for its baseline
1625     * @param hOffset  The distance along the path to add to the text's
1626     *                 starting position
1627     * @param vOffset  The distance above(-) or below(+) the path to position
1628     *                 the text
1629     * @param paint    The paint used for the text (e.g. color, size, style)
1630     */
1631    public void drawTextOnPath(char[] text, int index, int count, Path path,
1632            float hOffset, float vOffset, Paint paint) {
1633        if (index < 0 || index + count > text.length) {
1634            throw new ArrayIndexOutOfBoundsException();
1635        }
1636        native_drawTextOnPath(mNativeCanvas, text, index, count,
1637                path.ni(), hOffset, vOffset,
1638                paint.mBidiFlags, paint.mNativePaint);
1639    }
1640
1641    /**
1642     * Draw the text, with origin at (x,y), using the specified paint, along
1643     * the specified path. The paint's Align setting determins where along the
1644     * path to start the text.
1645     *
1646     * @param text     The text to be drawn
1647     * @param path     The path the text should follow for its baseline
1648     * @param hOffset  The distance along the path to add to the text's
1649     *                 starting position
1650     * @param vOffset  The distance above(-) or below(+) the path to position
1651     *                 the text
1652     * @param paint    The paint used for the text (e.g. color, size, style)
1653     */
1654    public void drawTextOnPath(String text, Path path, float hOffset, float vOffset, Paint paint) {
1655        if (text.length() > 0) {
1656            native_drawTextOnPath(mNativeCanvas, text, path.ni(), hOffset, vOffset,
1657                    paint.mBidiFlags, paint.mNativePaint);
1658        }
1659    }
1660
1661    /**
1662     * Save the canvas state, draw the picture, and restore the canvas state.
1663     * This differs from picture.draw(canvas), which does not perform any
1664     * save/restore.
1665     *
1666     * <p>
1667     * <strong>Note:</strong> This forces the picture to internally call
1668     * {@link Picture#endRecording} in order to prepare for playback.
1669     *
1670     * @param picture  The picture to be drawn
1671     */
1672    public void drawPicture(Picture picture) {
1673        picture.endRecording();
1674        int restoreCount = save();
1675        picture.draw(this);
1676        restoreToCount(restoreCount);
1677    }
1678
1679    /**
1680     * Draw the picture, stretched to fit into the dst rectangle.
1681     */
1682    public void drawPicture(Picture picture, RectF dst) {
1683        save();
1684        translate(dst.left, dst.top);
1685        if (picture.getWidth() > 0 && picture.getHeight() > 0) {
1686            scale(dst.width() / picture.getWidth(), dst.height() / picture.getHeight());
1687        }
1688        drawPicture(picture);
1689        restore();
1690    }
1691
1692    /**
1693     * Draw the picture, stretched to fit into the dst rectangle.
1694     */
1695    public void drawPicture(Picture picture, Rect dst) {
1696        save();
1697        translate(dst.left, dst.top);
1698        if (picture.getWidth() > 0 && picture.getHeight() > 0) {
1699            scale((float) dst.width() / picture.getWidth(),
1700                    (float) dst.height() / picture.getHeight());
1701        }
1702        drawPicture(picture);
1703        restore();
1704    }
1705
1706    /**
1707     * Releases the resources associated with this canvas.
1708     *
1709     * @hide
1710     */
1711    public void release() {
1712        mFinalizer.dispose();
1713    }
1714
1715    /**
1716     * Free up as much memory as possible from private caches (e.g. fonts, images)
1717     *
1718     * @hide
1719     */
1720    public static native void freeCaches();
1721
1722    /**
1723     * Free up text layout caches
1724     *
1725     * @hide
1726     */
1727    public static native void freeTextLayoutCaches();
1728
1729    private static native long initRaster(long nativeBitmapOrZero);
1730    private static native void copyNativeCanvasState(long nativeSrcCanvas,
1731                                                     long nativeDstCanvas);
1732    private static native int native_saveLayer(long nativeCanvas,
1733                                               RectF bounds,
1734                                               long nativePaint,
1735                                               int layerFlags);
1736    private static native int native_saveLayer(long nativeCanvas, float l,
1737                                               float t, float r, float b,
1738                                               long nativePaint,
1739                                               int layerFlags);
1740    private static native int native_saveLayerAlpha(long nativeCanvas,
1741                                                    RectF bounds, int alpha,
1742                                                    int layerFlags);
1743    private static native int native_saveLayerAlpha(long nativeCanvas, float l,
1744                                                    float t, float r, float b,
1745                                                    int alpha, int layerFlags);
1746
1747    private static native void native_concat(long nativeCanvas,
1748                                             long nativeMatrix);
1749    private static native void native_setMatrix(long nativeCanvas,
1750                                                long nativeMatrix);
1751    private static native boolean native_clipRect(long nativeCanvas,
1752                                                  float left, float top,
1753                                                  float right, float bottom,
1754                                                  int regionOp);
1755    private static native boolean native_clipPath(long nativeCanvas,
1756                                                  long nativePath,
1757                                                  int regionOp);
1758    private static native boolean native_clipRegion(long nativeCanvas,
1759                                                    long nativeRegion,
1760                                                    int regionOp);
1761    private static native void nativeSetDrawFilter(long nativeCanvas,
1762                                                   long nativeFilter);
1763    private static native boolean native_getClipBounds(long nativeCanvas,
1764                                                       Rect bounds);
1765    private static native void native_getCTM(long nativeCanvas,
1766                                             long nativeMatrix);
1767    private static native boolean native_quickReject(long nativeCanvas,
1768                                                     RectF rect);
1769    private static native boolean native_quickReject(long nativeCanvas,
1770                                                     long nativePath);
1771    private static native boolean native_quickReject(long nativeCanvas,
1772                                                     float left, float top,
1773                                                     float right, float bottom);
1774    private static native void native_drawRGB(long nativeCanvas, int r, int g,
1775                                              int b);
1776    private static native void native_drawARGB(long nativeCanvas, int a, int r,
1777                                               int g, int b);
1778    private static native void native_drawColor(long nativeCanvas, int color);
1779    private static native void native_drawColor(long nativeCanvas, int color,
1780                                                int mode);
1781    private static native void native_drawPaint(long nativeCanvas,
1782                                                long nativePaint);
1783    private static native void native_drawLine(long nativeCanvas, float startX,
1784                                               float startY, float stopX,
1785                                               float stopY, long nativePaint);
1786    private static native void native_drawRect(long nativeCanvas, RectF rect,
1787                                               long nativePaint);
1788    private static native void native_drawRect(long nativeCanvas, float left,
1789                                               float top, float right,
1790                                               float bottom,
1791                                               long nativePaint);
1792    private static native void native_drawOval(long nativeCanvas, RectF oval,
1793                                               long nativePaint);
1794    private static native void native_drawCircle(long nativeCanvas, float cx,
1795                                                 float cy, float radius,
1796                                                 long nativePaint);
1797    private static native void native_drawArc(long nativeCanvas, RectF oval,
1798                                              float startAngle, float sweep,
1799                                              boolean useCenter,
1800                                              long nativePaint);
1801    private static native void native_drawRoundRect(long nativeCanvas,
1802                                                    RectF rect, float rx,
1803                                                    float ry, long nativePaint);
1804    private static native void native_drawPath(long nativeCanvas,
1805                                               long nativePath,
1806                                               long nativePaint);
1807    private native void native_drawBitmap(long nativeCanvas, long nativeBitmap,
1808                                                 float left, float top,
1809                                                 long nativePaintOrZero,
1810                                                 int canvasDensity,
1811                                                 int screenDensity,
1812                                                 int bitmapDensity);
1813    private native void native_drawBitmap(long nativeCanvas, long nativeBitmap,
1814                                                 Rect src, RectF dst,
1815                                                 long nativePaintOrZero,
1816                                                 int screenDensity,
1817                                                 int bitmapDensity);
1818    private static native void native_drawBitmap(long nativeCanvas,
1819                                                 long nativeBitmap,
1820                                                 Rect src, Rect dst,
1821                                                 long nativePaintOrZero,
1822                                                 int screenDensity,
1823                                                 int bitmapDensity);
1824    private static native void native_drawBitmap(long nativeCanvas, int[] colors,
1825                                                int offset, int stride, float x,
1826                                                 float y, int width, int height,
1827                                                 boolean hasAlpha,
1828                                                 long nativePaintOrZero);
1829    private static native void nativeDrawBitmapMatrix(long nativeCanvas,
1830                                                      long nativeBitmap,
1831                                                      long nativeMatrix,
1832                                                      long nativePaint);
1833    private static native void nativeDrawBitmapMesh(long nativeCanvas,
1834                                                    long nativeBitmap,
1835                                                    int meshWidth, int meshHeight,
1836                                                    float[] verts, int vertOffset,
1837                                                    int[] colors, int colorOffset,
1838                                                    long nativePaint);
1839    private static native void nativeDrawVertices(long nativeCanvas, int mode, int n,
1840                   float[] verts, int vertOffset, float[] texs, int texOffset,
1841                   int[] colors, int colorOffset, short[] indices,
1842                   int indexOffset, int indexCount, long nativePaint);
1843
1844    private static native void native_drawText(long nativeCanvas, char[] text,
1845                                               int index, int count, float x,
1846                                               float y, int flags, long nativePaint,
1847                                               long nativeTypeface);
1848    private static native void native_drawText(long nativeCanvas, String text,
1849                                               int start, int end, float x,
1850                                               float y, int flags, long nativePaint,
1851                                               long nativeTypeface);
1852
1853    private static native void native_drawTextRun(long nativeCanvas, String text,
1854            int start, int end, int contextStart, int contextEnd,
1855            float x, float y, int flags, long nativePaint, long nativeTypeface);
1856
1857    private static native void native_drawTextRun(long nativeCanvas, char[] text,
1858            int start, int count, int contextStart, int contextCount,
1859            float x, float y, int flags, long nativePaint, long nativeTypeface);
1860
1861    private static native void native_drawPosText(long nativeCanvas,
1862                                                  char[] text, int index,
1863                                                  int count, float[] pos,
1864                                                  long nativePaint);
1865    private static native void native_drawPosText(long nativeCanvas,
1866                                                  String text, float[] pos,
1867                                                  long nativePaint);
1868    private static native void native_drawTextOnPath(long nativeCanvas,
1869                                                     char[] text, int index,
1870                                                     int count, long nativePath,
1871                                                     float hOffset,
1872                                                     float vOffset, int bidiFlags,
1873                                                     long nativePaint);
1874    private static native void native_drawTextOnPath(long nativeCanvas,
1875                                                     String text, long nativePath,
1876                                                     float hOffset,
1877                                                     float vOffset,
1878                                                     int flags, long nativePaint);
1879    private static native void finalizer(long nativeCanvas);
1880}
1881