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