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