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