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