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