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