Canvas.java revision edca320a2b42011f98c308fdf25fc0494c6a5454
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 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(min=4,multiple=2) float[] pts, int offset, int count, Paint paint) {
1083        native_drawLines(mNativeCanvasWrapper, pts, offset, count, paint.getNativeInstance());
1084    }
1085
1086    public void drawLines(@Size(min=4,multiple=2) @NonNull float[] pts, @NonNull Paint paint) {
1087        drawLines(pts, 0, pts.length, paint);
1088    }
1089
1090    /**
1091     * Draw the specified Rect using the specified paint. The rectangle will
1092     * be filled or framed based on the Style in the paint.
1093     *
1094     * @param rect  The rect to be drawn
1095     * @param paint The paint used to draw the rect
1096     */
1097    public void drawRect(@NonNull RectF rect, @NonNull Paint paint) {
1098        native_drawRect(mNativeCanvasWrapper,
1099                rect.left, rect.top, rect.right, rect.bottom, paint.getNativeInstance());
1100    }
1101
1102    /**
1103     * Draw the specified Rect using the specified Paint. The rectangle
1104     * will be filled or framed based on the Style in the paint.
1105     *
1106     * @param r        The rectangle to be drawn.
1107     * @param paint    The paint used to draw the rectangle
1108     */
1109    public void drawRect(@NonNull Rect r, @NonNull Paint paint) {
1110        drawRect(r.left, r.top, r.right, r.bottom, paint);
1111    }
1112
1113
1114    /**
1115     * Draw the specified Rect using the specified paint. The rectangle will
1116     * be filled or framed based on the Style in the paint.
1117     *
1118     * @param left   The left side of the rectangle to be drawn
1119     * @param top    The top side of the rectangle to be drawn
1120     * @param right  The right side of the rectangle to be drawn
1121     * @param bottom The bottom side of the rectangle to be drawn
1122     * @param paint  The paint used to draw the rect
1123     */
1124    public void drawRect(float left, float top, float right, float bottom, @NonNull Paint paint) {
1125        native_drawRect(mNativeCanvasWrapper, left, top, right, bottom, paint.getNativeInstance());
1126    }
1127
1128    /**
1129     * Draw the specified oval using the specified paint. The oval will be
1130     * filled or framed based on the Style in the paint.
1131     *
1132     * @param oval The rectangle bounds of the oval to be drawn
1133     */
1134    public void drawOval(@NonNull RectF oval, @NonNull Paint paint) {
1135        if (oval == null) {
1136            throw new NullPointerException();
1137        }
1138        drawOval(oval.left, oval.top, oval.right, oval.bottom, paint);
1139    }
1140
1141    /**
1142     * Draw the specified oval using the specified paint. The oval will be
1143     * filled or framed based on the Style in the paint.
1144     */
1145    public void drawOval(float left, float top, float right, float bottom, @NonNull Paint paint) {
1146        native_drawOval(mNativeCanvasWrapper, left, top, right, bottom, paint.getNativeInstance());
1147    }
1148
1149    /**
1150     * Draw the specified circle using the specified paint. If radius is <= 0,
1151     * then nothing will be drawn. The circle will be filled or framed based
1152     * on the Style in the paint.
1153     *
1154     * @param cx     The x-coordinate of the center of the cirle to be drawn
1155     * @param cy     The y-coordinate of the center of the cirle to be drawn
1156     * @param radius The radius of the cirle to be drawn
1157     * @param paint  The paint used to draw the circle
1158     */
1159    public void drawCircle(float cx, float cy, float radius, @NonNull Paint paint) {
1160        native_drawCircle(mNativeCanvasWrapper, cx, cy, radius, paint.getNativeInstance());
1161    }
1162
1163    /**
1164     * <p>Draw the specified arc, which will be scaled to fit inside the
1165     * specified oval.</p>
1166     *
1167     * <p>If the start angle is negative or >= 360, the start angle is treated
1168     * as start angle modulo 360.</p>
1169     *
1170     * <p>If the sweep angle is >= 360, then the oval is drawn
1171     * completely. Note that this differs slightly from SkPath::arcTo, which
1172     * treats the sweep angle modulo 360. If the sweep angle is negative,
1173     * the sweep angle is treated as sweep angle modulo 360</p>
1174     *
1175     * <p>The arc is drawn clockwise. An angle of 0 degrees correspond to the
1176     * geometric angle of 0 degrees (3 o'clock on a watch.)</p>
1177     *
1178     * @param oval       The bounds of oval used to define the shape and size
1179     *                   of the arc
1180     * @param startAngle Starting angle (in degrees) where the arc begins
1181     * @param sweepAngle Sweep angle (in degrees) measured clockwise
1182     * @param useCenter If true, include the center of the oval in the arc, and
1183                        close it if it is being stroked. This will draw a wedge
1184     * @param paint      The paint used to draw the arc
1185     */
1186    public void drawArc(@NonNull RectF oval, float startAngle, float sweepAngle, boolean useCenter,
1187            @NonNull Paint paint) {
1188        drawArc(oval.left, oval.top, oval.right, oval.bottom, startAngle, sweepAngle, useCenter,
1189                paint);
1190    }
1191
1192    /**
1193     * <p>Draw the specified arc, which will be scaled to fit inside the
1194     * specified oval.</p>
1195     *
1196     * <p>If the start angle is negative or >= 360, the start angle is treated
1197     * as start angle modulo 360.</p>
1198     *
1199     * <p>If the sweep angle is >= 360, then the oval is drawn
1200     * completely. Note that this differs slightly from SkPath::arcTo, which
1201     * treats the sweep angle modulo 360. If the sweep angle is negative,
1202     * the sweep angle is treated as sweep angle modulo 360</p>
1203     *
1204     * <p>The arc is drawn clockwise. An angle of 0 degrees correspond to the
1205     * geometric angle of 0 degrees (3 o'clock on a watch.)</p>
1206     *
1207     * @param startAngle Starting angle (in degrees) where the arc begins
1208     * @param sweepAngle Sweep angle (in degrees) measured clockwise
1209     * @param useCenter If true, include the center of the oval in the arc, and
1210                        close it if it is being stroked. This will draw a wedge
1211     * @param paint      The paint used to draw the arc
1212     */
1213    public void drawArc(float left, float top, float right, float bottom, float startAngle,
1214            float sweepAngle, boolean useCenter, @NonNull Paint paint) {
1215        native_drawArc(mNativeCanvasWrapper, left, top, right, bottom, startAngle, sweepAngle,
1216                useCenter, paint.getNativeInstance());
1217    }
1218
1219    /**
1220     * Draw the specified round-rect using the specified paint. The roundrect
1221     * will be filled or framed based on the Style in the paint.
1222     *
1223     * @param rect  The rectangular bounds of the roundRect to be drawn
1224     * @param rx    The x-radius of the oval used to round the corners
1225     * @param ry    The y-radius of the oval used to round the corners
1226     * @param paint The paint used to draw the roundRect
1227     */
1228    public void drawRoundRect(@NonNull RectF rect, float rx, float ry, @NonNull Paint paint) {
1229        drawRoundRect(rect.left, rect.top, rect.right, rect.bottom, rx, ry, paint);
1230    }
1231
1232    /**
1233     * Draw the specified round-rect using the specified paint. The roundrect
1234     * will be filled or framed based on the Style in the paint.
1235     *
1236     * @param rx    The x-radius of the oval used to round the corners
1237     * @param ry    The y-radius of the oval used to round the corners
1238     * @param paint The paint used to draw the roundRect
1239     */
1240    public void drawRoundRect(float left, float top, float right, float bottom, float rx, float ry,
1241            @NonNull Paint paint) {
1242        native_drawRoundRect(mNativeCanvasWrapper, left, top, right, bottom, rx, ry, paint.getNativeInstance());
1243    }
1244
1245    /**
1246     * Draw the specified path using the specified paint. The path will be
1247     * filled or framed based on the Style in the paint.
1248     *
1249     * @param path  The path to be drawn
1250     * @param paint The paint used to draw the path
1251     */
1252    public void drawPath(@NonNull Path path, @NonNull Paint paint) {
1253        if (path.isSimplePath && path.rects != null) {
1254            native_drawRegion(mNativeCanvasWrapper, path.rects.mNativeRegion, paint.getNativeInstance());
1255        } else {
1256            native_drawPath(mNativeCanvasWrapper, path.ni(), paint.getNativeInstance());
1257        }
1258    }
1259
1260    /**
1261     * @hide
1262     */
1263    protected static void throwIfCannotDraw(Bitmap bitmap) {
1264        if (bitmap.isRecycled()) {
1265            throw new RuntimeException("Canvas: trying to use a recycled bitmap " + bitmap);
1266        }
1267        if (!bitmap.isPremultiplied() && bitmap.getConfig() == Bitmap.Config.ARGB_8888 &&
1268                bitmap.hasAlpha()) {
1269            throw new RuntimeException("Canvas: trying to use a non-premultiplied bitmap "
1270                    + bitmap);
1271        }
1272    }
1273
1274    /**
1275     * Draws the specified bitmap as an N-patch (most often, a 9-patches.)
1276     *
1277     * @param patch The ninepatch object to render
1278     * @param dst The destination rectangle.
1279     * @param paint The paint to draw the bitmap with. may be null
1280     *
1281     * @hide
1282     */
1283    public void drawPatch(@NonNull NinePatch patch, @NonNull Rect dst, @Nullable Paint paint) {
1284        final long nativePaint = paint == null ? 0 : paint.getNativeInstance();
1285        native_drawNinePatch(mNativeCanvasWrapper, patch.getBitmap(), patch.mNativeChunk,
1286                dst.left, dst.top, dst.right, dst.bottom, nativePaint,
1287                mDensity, patch.getDensity());
1288    }
1289
1290    /**
1291     * Draws the specified bitmap as an N-patch (most often, a 9-patches.)
1292     *
1293     * @param patch The ninepatch object to render
1294     * @param dst The destination rectangle.
1295     * @param paint The paint to draw the bitmap with. may be null
1296     *
1297     * @hide
1298     */
1299    public void drawPatch(@NonNull NinePatch patch, @NonNull RectF dst, @Nullable Paint paint) {
1300        final long nativePaint = paint == null ? 0 : paint.getNativeInstance();
1301        native_drawNinePatch(mNativeCanvasWrapper, patch.getBitmap(), patch.mNativeChunk,
1302                dst.left, dst.top, dst.right, dst.bottom, nativePaint,
1303                mDensity, patch.getDensity());
1304    }
1305
1306    /**
1307     * Draw the specified bitmap, with its top/left corner at (x,y), using
1308     * the specified paint, transformed by the current matrix.
1309     *
1310     * <p>Note: if the paint contains a maskfilter that generates a mask which
1311     * extends beyond the bitmap's original width/height (e.g. BlurMaskFilter),
1312     * then the bitmap will be drawn as if it were in a Shader with CLAMP mode.
1313     * Thus the color outside of the original width/height will be the edge
1314     * color replicated.
1315     *
1316     * <p>If the bitmap and canvas have different densities, this function
1317     * will take care of automatically scaling the bitmap to draw at the
1318     * same density as the canvas.
1319     *
1320     * @param bitmap The bitmap to be drawn
1321     * @param left   The position of the left side of the bitmap being drawn
1322     * @param top    The position of the top side of the bitmap being drawn
1323     * @param paint  The paint used to draw the bitmap (may be null)
1324     */
1325    public void drawBitmap(@NonNull Bitmap bitmap, float left, float top, @Nullable Paint paint) {
1326        throwIfCannotDraw(bitmap);
1327        native_drawBitmap(mNativeCanvasWrapper, bitmap, left, top,
1328                paint != null ? paint.getNativeInstance() : 0, mDensity, mScreenDensity, bitmap.mDensity);
1329    }
1330
1331    /**
1332     * Draw the specified bitmap, scaling/translating automatically to fill
1333     * the destination rectangle. If the source rectangle is not null, it
1334     * specifies the subset of the bitmap to draw.
1335     *
1336     * <p>Note: if the paint contains a maskfilter that generates a mask which
1337     * extends beyond the bitmap's original width/height (e.g. BlurMaskFilter),
1338     * then the bitmap will be drawn as if it were in a Shader with CLAMP mode.
1339     * Thus the color outside of the original width/height will be the edge
1340     * color replicated.
1341     *
1342     * <p>This function <em>ignores the density associated with the bitmap</em>.
1343     * This is because the source and destination rectangle coordinate
1344     * spaces are in their respective densities, so must already have the
1345     * appropriate scaling factor applied.
1346     *
1347     * @param bitmap The bitmap to be drawn
1348     * @param src    May be null. The subset of the bitmap to be drawn
1349     * @param dst    The rectangle that the bitmap will be scaled/translated
1350     *               to fit into
1351     * @param paint  May be null. The paint used to draw the bitmap
1352     */
1353    public void drawBitmap(@NonNull Bitmap bitmap, @Nullable Rect src, @NonNull RectF dst,
1354            @Nullable Paint paint) {
1355      if (dst == null) {
1356          throw new NullPointerException();
1357      }
1358      throwIfCannotDraw(bitmap);
1359      final long nativePaint = paint == null ? 0 : paint.getNativeInstance();
1360
1361      float left, top, right, bottom;
1362      if (src == null) {
1363          left = top = 0;
1364          right = bitmap.getWidth();
1365          bottom = bitmap.getHeight();
1366      } else {
1367          left = src.left;
1368          right = src.right;
1369          top = src.top;
1370          bottom = src.bottom;
1371      }
1372
1373      native_drawBitmap(mNativeCanvasWrapper, bitmap, left, top, right, bottom,
1374              dst.left, dst.top, dst.right, dst.bottom, nativePaint, mScreenDensity,
1375              bitmap.mDensity);
1376  }
1377
1378    /**
1379     * Draw the specified bitmap, scaling/translating automatically to fill
1380     * the destination rectangle. If the source rectangle is not null, it
1381     * specifies the subset of the bitmap to draw.
1382     *
1383     * <p>Note: if the paint contains a maskfilter that generates a mask which
1384     * extends beyond the bitmap's original width/height (e.g. BlurMaskFilter),
1385     * then the bitmap will be drawn as if it were in a Shader with CLAMP mode.
1386     * Thus the color outside of the original width/height will be the edge
1387     * color replicated.
1388     *
1389     * <p>This function <em>ignores the density associated with the bitmap</em>.
1390     * This is because the source and destination rectangle coordinate
1391     * spaces are in their respective densities, so must already have the
1392     * appropriate scaling factor applied.
1393     *
1394     * @param bitmap The bitmap to be drawn
1395     * @param src    May be null. The subset of the bitmap to be drawn
1396     * @param dst    The rectangle that the bitmap will be scaled/translated
1397     *               to fit into
1398     * @param paint  May be null. The paint used to draw the bitmap
1399     */
1400    public void drawBitmap(@NonNull Bitmap bitmap, @Nullable Rect src, @NonNull Rect dst,
1401            @Nullable Paint paint) {
1402        if (dst == null) {
1403            throw new NullPointerException();
1404        }
1405        throwIfCannotDraw(bitmap);
1406        final long nativePaint = paint == null ? 0 : paint.getNativeInstance();
1407
1408        int left, top, right, bottom;
1409        if (src == null) {
1410            left = top = 0;
1411            right = bitmap.getWidth();
1412            bottom = bitmap.getHeight();
1413        } else {
1414            left = src.left;
1415            right = src.right;
1416            top = src.top;
1417            bottom = src.bottom;
1418        }
1419
1420        native_drawBitmap(mNativeCanvasWrapper, bitmap, left, top, right, bottom,
1421            dst.left, dst.top, dst.right, dst.bottom, nativePaint, mScreenDensity,
1422            bitmap.mDensity);
1423    }
1424
1425    /**
1426     * Treat the specified array of colors as a bitmap, and draw it. This gives
1427     * the same result as first creating a bitmap from the array, and then
1428     * drawing it, but this method avoids explicitly creating a bitmap object
1429     * which can be more efficient if the colors are changing often.
1430     *
1431     * @param colors Array of colors representing the pixels of the bitmap
1432     * @param offset Offset into the array of colors for the first pixel
1433     * @param stride The number of colors in the array between rows (must be
1434     *               >= width or <= -width).
1435     * @param x The X coordinate for where to draw the bitmap
1436     * @param y The Y coordinate for where to draw the bitmap
1437     * @param width The width of the bitmap
1438     * @param height The height of the bitmap
1439     * @param hasAlpha True if the alpha channel of the colors contains valid
1440     *                 values. If false, the alpha byte is ignored (assumed to
1441     *                 be 0xFF for every pixel).
1442     * @param paint  May be null. The paint used to draw the bitmap
1443     *
1444     * @deprecated Usage with a {@link #isHardwareAccelerated() hardware accelerated} canvas
1445     * requires an internal copy of color buffer contents every time this method is called. Using a
1446     * Bitmap avoids this copy, and allows the application to more explicitly control the lifetime
1447     * and copies of pixel data.
1448     */
1449    @Deprecated
1450    public void drawBitmap(@NonNull int[] colors, int offset, int stride, float x, float y,
1451            int width, int height, boolean hasAlpha, @Nullable Paint paint) {
1452        // check for valid input
1453        if (width < 0) {
1454            throw new IllegalArgumentException("width must be >= 0");
1455        }
1456        if (height < 0) {
1457            throw new IllegalArgumentException("height must be >= 0");
1458        }
1459        if (Math.abs(stride) < width) {
1460            throw new IllegalArgumentException("abs(stride) must be >= width");
1461        }
1462        int lastScanline = offset + (height - 1) * stride;
1463        int length = colors.length;
1464        if (offset < 0 || (offset + width > length) || lastScanline < 0
1465                || (lastScanline + width > length)) {
1466            throw new ArrayIndexOutOfBoundsException();
1467        }
1468        // quick escape if there's nothing to draw
1469        if (width == 0 || height == 0) {
1470            return;
1471        }
1472        // punch down to native for the actual draw
1473        native_drawBitmap(mNativeCanvasWrapper, colors, offset, stride, x, y, width, height, hasAlpha,
1474                paint != null ? paint.getNativeInstance() : 0);
1475    }
1476
1477    /**
1478     * Legacy version of drawBitmap(int[] colors, ...) that took ints for x,y
1479     *
1480     * @deprecated Usage with a {@link #isHardwareAccelerated() hardware accelerated} canvas
1481     * requires an internal copy of color buffer contents every time this method is called. Using a
1482     * Bitmap avoids this copy, and allows the application to more explicitly control the lifetime
1483     * and copies of pixel data.
1484     */
1485    @Deprecated
1486    public void drawBitmap(@NonNull int[] colors, int offset, int stride, int x, int y,
1487            int width, int height, boolean hasAlpha, @Nullable Paint paint) {
1488        // call through to the common float version
1489        drawBitmap(colors, offset, stride, (float)x, (float)y, width, height,
1490                   hasAlpha, paint);
1491    }
1492
1493    /**
1494     * Draw the bitmap using the specified matrix.
1495     *
1496     * @param bitmap The bitmap to draw
1497     * @param matrix The matrix used to transform the bitmap when it is drawn
1498     * @param paint  May be null. The paint used to draw the bitmap
1499     */
1500    public void drawBitmap(@NonNull Bitmap bitmap, @NonNull Matrix matrix, @Nullable Paint paint) {
1501        nativeDrawBitmapMatrix(mNativeCanvasWrapper, bitmap, matrix.ni(),
1502                paint != null ? paint.getNativeInstance() : 0);
1503    }
1504
1505    /**
1506     * @hide
1507     */
1508    protected static void checkRange(int length, int offset, int count) {
1509        if ((offset | count) < 0 || offset + count > length) {
1510            throw new ArrayIndexOutOfBoundsException();
1511        }
1512    }
1513
1514    /**
1515     * Draw the bitmap through the mesh, where mesh vertices are evenly
1516     * distributed across the bitmap. There are meshWidth+1 vertices across, and
1517     * meshHeight+1 vertices down. The verts array is accessed in row-major
1518     * order, so that the first meshWidth+1 vertices are distributed across the
1519     * top of the bitmap from left to right. A more general version of this
1520     * method is drawVertices().
1521     *
1522     * @param bitmap The bitmap to draw using the mesh
1523     * @param meshWidth The number of columns in the mesh. Nothing is drawn if
1524     *                  this is 0
1525     * @param meshHeight The number of rows in the mesh. Nothing is drawn if
1526     *                   this is 0
1527     * @param verts Array of x,y pairs, specifying where the mesh should be
1528     *              drawn. There must be at least
1529     *              (meshWidth+1) * (meshHeight+1) * 2 + vertOffset values
1530     *              in the array
1531     * @param vertOffset Number of verts elements to skip before drawing
1532     * @param colors May be null. Specifies a color at each vertex, which is
1533     *               interpolated across the cell, and whose values are
1534     *               multiplied by the corresponding bitmap colors. If not null,
1535     *               there must be at least (meshWidth+1) * (meshHeight+1) +
1536     *               colorOffset values in the array.
1537     * @param colorOffset Number of color elements to skip before drawing
1538     * @param paint  May be null. The paint used to draw the bitmap
1539     */
1540    public void drawBitmapMesh(@NonNull Bitmap bitmap, int meshWidth, int meshHeight,
1541            @NonNull float[] verts, int vertOffset, @Nullable int[] colors, int colorOffset,
1542            @Nullable Paint paint) {
1543        if ((meshWidth | meshHeight | vertOffset | colorOffset) < 0) {
1544            throw new ArrayIndexOutOfBoundsException();
1545        }
1546        if (meshWidth == 0 || meshHeight == 0) {
1547            return;
1548        }
1549        int count = (meshWidth + 1) * (meshHeight + 1);
1550        // we mul by 2 since we need two floats per vertex
1551        checkRange(verts.length, vertOffset, count * 2);
1552        if (colors != null) {
1553            // no mul by 2, since we need only 1 color per vertex
1554            checkRange(colors.length, colorOffset, count);
1555        }
1556        nativeDrawBitmapMesh(mNativeCanvasWrapper, bitmap, meshWidth, meshHeight,
1557                verts, vertOffset, colors, colorOffset,
1558                paint != null ? paint.getNativeInstance() : 0);
1559    }
1560
1561    public enum VertexMode {
1562        TRIANGLES(0),
1563        TRIANGLE_STRIP(1),
1564        TRIANGLE_FAN(2);
1565
1566        VertexMode(int nativeInt) {
1567            this.nativeInt = nativeInt;
1568        }
1569
1570        /**
1571         * @hide
1572         */
1573        public final int nativeInt;
1574    }
1575
1576    /**
1577     * Draw the array of vertices, interpreted as triangles (based on mode). The
1578     * verts array is required, and specifies the x,y pairs for each vertex. If
1579     * texs is non-null, then it is used to specify the coordinate in shader
1580     * coordinates to use at each vertex (the paint must have a shader in this
1581     * case). If there is no texs array, but there is a color array, then each
1582     * color is interpolated across its corresponding triangle in a gradient. If
1583     * both texs and colors arrays are present, then they behave as before, but
1584     * the resulting color at each pixels is the result of multiplying the
1585     * colors from the shader and the color-gradient together. The indices array
1586     * is optional, but if it is present, then it is used to specify the index
1587     * of each triangle, rather than just walking through the arrays in order.
1588     *
1589     * @param mode How to interpret the array of vertices
1590     * @param vertexCount The number of values in the vertices array (and
1591     *      corresponding texs and colors arrays if non-null). Each logical
1592     *      vertex is two values (x, y), vertexCount must be a multiple of 2.
1593     * @param verts Array of vertices for the mesh
1594     * @param vertOffset Number of values in the verts to skip before drawing.
1595     * @param texs May be null. If not null, specifies the coordinates to sample
1596     *      into the current shader (e.g. bitmap tile or gradient)
1597     * @param texOffset Number of values in texs to skip before drawing.
1598     * @param colors May be null. If not null, specifies a color for each
1599     *      vertex, to be interpolated across the triangle.
1600     * @param colorOffset Number of values in colors to skip before drawing.
1601     * @param indices If not null, array of indices to reference into the
1602     *      vertex (texs, colors) array.
1603     * @param indexCount number of entries in the indices array (if not null).
1604     * @param paint Specifies the shader to use if the texs array is non-null.
1605     */
1606    public void drawVertices(@NonNull VertexMode mode, int vertexCount, @NonNull float[] verts,
1607            int vertOffset, @Nullable float[] texs, int texOffset, @Nullable int[] colors,
1608            int colorOffset, @Nullable short[] indices, int indexOffset, int indexCount,
1609            @NonNull Paint paint) {
1610        checkRange(verts.length, vertOffset, vertexCount);
1611        if (isHardwareAccelerated()) {
1612            return;
1613        }
1614        if (texs != null) {
1615            checkRange(texs.length, texOffset, vertexCount);
1616        }
1617        if (colors != null) {
1618            checkRange(colors.length, colorOffset, vertexCount / 2);
1619        }
1620        if (indices != null) {
1621            checkRange(indices.length, indexOffset, indexCount);
1622        }
1623        nativeDrawVertices(mNativeCanvasWrapper, mode.nativeInt, vertexCount, verts,
1624                vertOffset, texs, texOffset, colors, colorOffset,
1625                indices, indexOffset, indexCount, paint.getNativeInstance());
1626    }
1627
1628    /**
1629     * Draw the text, with origin at (x,y), using the specified paint. The
1630     * origin is interpreted based on the Align setting in the paint.
1631     *
1632     * @param text  The text to be drawn
1633     * @param x     The x-coordinate of the origin of the text being drawn
1634     * @param y     The y-coordinate of the baseline of the text being drawn
1635     * @param paint The paint used for the text (e.g. color, size, style)
1636     */
1637    public void drawText(@NonNull char[] text, int index, int count, float x, float y,
1638            @NonNull Paint paint) {
1639        if ((index | count | (index + count) |
1640            (text.length - index - count)) < 0) {
1641            throw new IndexOutOfBoundsException();
1642        }
1643        native_drawText(mNativeCanvasWrapper, text, index, count, x, y, paint.mBidiFlags,
1644                paint.getNativeInstance(), paint.mNativeTypeface);
1645    }
1646
1647    /**
1648     * Draw the text, with origin at (x,y), using the specified paint. The
1649     * origin is interpreted based on the Align setting in the paint.
1650     *
1651     * @param text  The text to be drawn
1652     * @param x     The x-coordinate of the origin of the text being drawn
1653     * @param y     The y-coordinate of the baseline of the text being drawn
1654     * @param paint The paint used for the text (e.g. color, size, style)
1655     */
1656    public void drawText(@NonNull String text, float x, float y, @NonNull Paint paint) {
1657        native_drawText(mNativeCanvasWrapper, text, 0, text.length(), x, y, paint.mBidiFlags,
1658                paint.getNativeInstance(), paint.mNativeTypeface);
1659    }
1660
1661    /**
1662     * Draw the text, with origin at (x,y), using the specified paint.
1663     * The origin is interpreted based on the Align setting in the paint.
1664     *
1665     * @param text  The text to be drawn
1666     * @param start The index of the first character in text to draw
1667     * @param end   (end - 1) is the index of the last character in text to draw
1668     * @param x     The x-coordinate of the origin of the text being drawn
1669     * @param y     The y-coordinate of the baseline of the text being drawn
1670     * @param paint The paint used for the text (e.g. color, size, style)
1671     */
1672    public void drawText(@NonNull String text, int start, int end, float x, float y,
1673            @NonNull Paint paint) {
1674        if ((start | end | (end - start) | (text.length() - end)) < 0) {
1675            throw new IndexOutOfBoundsException();
1676        }
1677        native_drawText(mNativeCanvasWrapper, text, start, end, x, y, paint.mBidiFlags,
1678                paint.getNativeInstance(), paint.mNativeTypeface);
1679    }
1680
1681    /**
1682     * Draw the specified range of text, specified by start/end, with its
1683     * origin at (x,y), in the specified Paint. The origin is interpreted
1684     * based on the Align setting in the Paint.
1685     *
1686     * @param text     The text to be drawn
1687     * @param start    The index of the first character in text to draw
1688     * @param end      (end - 1) is the index of the last character in text
1689     *                 to draw
1690     * @param x        The x-coordinate of origin for where to draw the text
1691     * @param y        The y-coordinate of origin for where to draw the text
1692     * @param paint The paint used for the text (e.g. color, size, style)
1693     */
1694    public void drawText(@NonNull CharSequence text, int start, int end, float x, float y,
1695            @NonNull Paint paint) {
1696        if ((start | end | (end - start) | (text.length() - end)) < 0) {
1697            throw new IndexOutOfBoundsException();
1698        }
1699        if (text instanceof String || text instanceof SpannedString ||
1700            text instanceof SpannableString) {
1701            native_drawText(mNativeCanvasWrapper, text.toString(), start, end, x, y,
1702                    paint.mBidiFlags, paint.getNativeInstance(), paint.mNativeTypeface);
1703        } else if (text instanceof GraphicsOperations) {
1704            ((GraphicsOperations) text).drawText(this, start, end, x, y,
1705                    paint);
1706        } else {
1707            char[] buf = TemporaryBuffer.obtain(end - start);
1708            TextUtils.getChars(text, start, end, buf, 0);
1709            native_drawText(mNativeCanvasWrapper, buf, 0, end - start, x, y,
1710                    paint.mBidiFlags, paint.getNativeInstance(), paint.mNativeTypeface);
1711            TemporaryBuffer.recycle(buf);
1712        }
1713    }
1714
1715    /**
1716     * Draw a run of text, all in a single direction, with optional context for complex text
1717     * shaping.
1718     *
1719     * <p>See {@link #drawTextRun(CharSequence, int, int, int, int, float, float, boolean, Paint)}
1720     * for more details. This method uses a character array rather than CharSequence to
1721     * represent the string. Also, to be consistent with the pattern established in
1722     * {@link #drawText}, in this method {@code count} and {@code contextCount} are used rather
1723     * than offsets of the end position; {@code count = end - start, contextCount = contextEnd -
1724     * contextStart}.
1725     *
1726     * @param text the text to render
1727     * @param index the start of the text to render
1728     * @param count the count of chars to render
1729     * @param contextIndex the start of the context for shaping.  Must be
1730     *         no greater than index.
1731     * @param contextCount the number of characters in the context for shaping.
1732     *         contexIndex + contextCount must be no less than index + count.
1733     * @param x the x position at which to draw the text
1734     * @param y the y position at which to draw the text
1735     * @param isRtl whether the run is in RTL direction
1736     * @param paint the paint
1737     */
1738    public void drawTextRun(@NonNull char[] text, int index, int count, int contextIndex,
1739            int contextCount, float x, float y, boolean isRtl, @NonNull Paint paint) {
1740
1741        if (text == null) {
1742            throw new NullPointerException("text is null");
1743        }
1744        if (paint == null) {
1745            throw new NullPointerException("paint is null");
1746        }
1747        if ((index | count | contextIndex | contextCount | index - contextIndex
1748                | (contextIndex + contextCount) - (index + count)
1749                | text.length - (contextIndex + contextCount)) < 0) {
1750            throw new IndexOutOfBoundsException();
1751        }
1752
1753        native_drawTextRun(mNativeCanvasWrapper, text, index, count, contextIndex, contextCount,
1754                x, y, isRtl, paint.getNativeInstance(), paint.mNativeTypeface);
1755    }
1756
1757    /**
1758     * Draw a run of text, all in a single direction, with optional context for complex text
1759     * shaping.
1760     *
1761     * <p>The run of text includes the characters from {@code start} to {@code end} in the text. In
1762     * addition, the range {@code contextStart} to {@code contextEnd} is used as context for the
1763     * purpose of complex text shaping, such as Arabic text potentially shaped differently based on
1764     * the text next to it.
1765     *
1766     * <p>All text outside the range {@code contextStart..contextEnd} is ignored. The text between
1767     * {@code start} and {@code end} will be laid out and drawn.
1768     *
1769     * <p>The direction of the run is explicitly specified by {@code isRtl}. Thus, this method is
1770     * suitable only for runs of a single direction. Alignment of the text is as determined by the
1771     * Paint's TextAlign value. Further, {@code 0 <= contextStart <= start <= end <= contextEnd
1772     * <= text.length} must hold on entry.
1773     *
1774     * <p>Also see {@link android.graphics.Paint#getRunAdvance} for a corresponding method to
1775     * measure the text; the advance width of the text drawn matches the value obtained from that
1776     * method.
1777     *
1778     * @param text the text to render
1779     * @param start the start of the text to render. Data before this position
1780     *            can be used for shaping context.
1781     * @param end the end of the text to render. Data at or after this
1782     *            position can be used for shaping context.
1783     * @param contextStart the index of the start of the shaping context
1784     * @param contextEnd the index of the end of the shaping context
1785     * @param x the x position at which to draw the text
1786     * @param y the y position at which to draw the text
1787     * @param isRtl whether the run is in RTL direction
1788     * @param paint the paint
1789     *
1790     * @see #drawTextRun(char[], int, int, int, int, float, float, boolean, Paint)
1791     */
1792    public void drawTextRun(@NonNull CharSequence text, int start, int end, int contextStart,
1793            int contextEnd, float x, float y, boolean isRtl, @NonNull Paint paint) {
1794
1795        if (text == null) {
1796            throw new NullPointerException("text is null");
1797        }
1798        if (paint == null) {
1799            throw new NullPointerException("paint is null");
1800        }
1801        if ((start | end | contextStart | contextEnd | start - contextStart | end - start
1802                | contextEnd - end | text.length() - contextEnd) < 0) {
1803            throw new IndexOutOfBoundsException();
1804        }
1805
1806        if (text instanceof String || text instanceof SpannedString ||
1807                text instanceof SpannableString) {
1808            native_drawTextRun(mNativeCanvasWrapper, text.toString(), start, end, contextStart,
1809                    contextEnd, x, y, isRtl, paint.getNativeInstance(), paint.mNativeTypeface);
1810        } else if (text instanceof GraphicsOperations) {
1811            ((GraphicsOperations) text).drawTextRun(this, start, end,
1812                    contextStart, contextEnd, x, y, isRtl, paint);
1813        } else {
1814            int contextLen = contextEnd - contextStart;
1815            int len = end - start;
1816            char[] buf = TemporaryBuffer.obtain(contextLen);
1817            TextUtils.getChars(text, contextStart, contextEnd, buf, 0);
1818            native_drawTextRun(mNativeCanvasWrapper, buf, start - contextStart, len,
1819                    0, contextLen, x, y, isRtl, paint.getNativeInstance(), paint.mNativeTypeface);
1820            TemporaryBuffer.recycle(buf);
1821        }
1822    }
1823
1824    /**
1825     * Draw the text in the array, with each character's origin specified by
1826     * the pos array.
1827     *
1828     * This method does not support glyph composition and decomposition and
1829     * should therefore not be used to render complex scripts. It also doesn't
1830     * handle supplementary characters (eg emoji).
1831     *
1832     * @param text     The text to be drawn
1833     * @param index    The index of the first character to draw
1834     * @param count    The number of characters to draw, starting from index.
1835     * @param pos      Array of [x,y] positions, used to position each
1836     *                 character
1837     * @param paint    The paint used for the text (e.g. color, size, style)
1838     */
1839    @Deprecated
1840    public void drawPosText(@NonNull char[] text, int index, int count,
1841            @NonNull @Size(multiple=2) float[] pos,
1842            @NonNull Paint paint) {
1843        if (index < 0 || index + count > text.length || count*2 > pos.length) {
1844            throw new IndexOutOfBoundsException();
1845        }
1846        for (int i = 0; i < count; i++) {
1847            drawText(text, index + i, 1, pos[i * 2], pos[i * 2 + 1], paint);
1848        }
1849    }
1850
1851    /**
1852     * Draw the text in the array, with each character's origin specified by
1853     * the pos array.
1854     *
1855     * This method does not support glyph composition and decomposition and
1856     * should therefore not be used to render complex scripts. It also doesn't
1857     * handle supplementary characters (eg emoji).
1858     *
1859     * @param text  The text to be drawn
1860     * @param pos   Array of [x,y] positions, used to position each character
1861     * @param paint The paint used for the text (e.g. color, size, style)
1862     */
1863    @Deprecated
1864    public void drawPosText(@NonNull String text, @NonNull @Size(multiple=2) float[] pos,
1865            @NonNull Paint paint) {
1866        drawPosText(text.toCharArray(), 0, text.length(), pos, paint);
1867    }
1868
1869    /**
1870     * Draw the text, with origin at (x,y), using the specified paint, along
1871     * the specified path. The paint's Align setting determins where along the
1872     * path to start the text.
1873     *
1874     * @param text     The text to be drawn
1875     * @param path     The path the text should follow for its baseline
1876     * @param hOffset  The distance along the path to add to the text's
1877     *                 starting position
1878     * @param vOffset  The distance above(-) or below(+) the path to position
1879     *                 the text
1880     * @param paint    The paint used for the text (e.g. color, size, style)
1881     */
1882    public void drawTextOnPath(@NonNull char[] text, int index, int count, @NonNull Path path,
1883            float hOffset, float vOffset, @NonNull Paint paint) {
1884        if (index < 0 || index + count > text.length) {
1885            throw new ArrayIndexOutOfBoundsException();
1886        }
1887        native_drawTextOnPath(mNativeCanvasWrapper, text, index, count,
1888                path.ni(), hOffset, vOffset,
1889                paint.mBidiFlags, paint.getNativeInstance(), paint.mNativeTypeface);
1890    }
1891
1892    /**
1893     * Draw the text, with origin at (x,y), using the specified paint, along
1894     * the specified path. The paint's Align setting determins where along the
1895     * path to start the text.
1896     *
1897     * @param text     The text to be drawn
1898     * @param path     The path the text should follow for its baseline
1899     * @param hOffset  The distance along the path to add to the text's
1900     *                 starting position
1901     * @param vOffset  The distance above(-) or below(+) the path to position
1902     *                 the text
1903     * @param paint    The paint used for the text (e.g. color, size, style)
1904     */
1905    public void drawTextOnPath(@NonNull String text, @NonNull Path path, float hOffset,
1906            float vOffset, @NonNull Paint paint) {
1907        if (text.length() > 0) {
1908            native_drawTextOnPath(mNativeCanvasWrapper, text, path.ni(), hOffset, vOffset,
1909                    paint.mBidiFlags, paint.getNativeInstance(), paint.mNativeTypeface);
1910        }
1911    }
1912
1913    /**
1914     * Save the canvas state, draw the picture, and restore the canvas state.
1915     * This differs from picture.draw(canvas), which does not perform any
1916     * save/restore.
1917     *
1918     * <p>
1919     * <strong>Note:</strong> This forces the picture to internally call
1920     * {@link Picture#endRecording} in order to prepare for playback.
1921     *
1922     * @param picture  The picture to be drawn
1923     */
1924    public void drawPicture(@NonNull Picture picture) {
1925        picture.endRecording();
1926        int restoreCount = save();
1927        picture.draw(this);
1928        restoreToCount(restoreCount);
1929    }
1930
1931    /**
1932     * Draw the picture, stretched to fit into the dst rectangle.
1933     */
1934    public void drawPicture(@NonNull Picture picture, @NonNull RectF dst) {
1935        save();
1936        translate(dst.left, dst.top);
1937        if (picture.getWidth() > 0 && picture.getHeight() > 0) {
1938            scale(dst.width() / picture.getWidth(), dst.height() / picture.getHeight());
1939        }
1940        drawPicture(picture);
1941        restore();
1942    }
1943
1944    /**
1945     * Draw the picture, stretched to fit into the dst rectangle.
1946     */
1947    public void drawPicture(@NonNull Picture picture, @NonNull Rect dst) {
1948        save();
1949        translate(dst.left, dst.top);
1950        if (picture.getWidth() > 0 && picture.getHeight() > 0) {
1951            scale((float) dst.width() / picture.getWidth(),
1952                    (float) dst.height() / picture.getHeight());
1953        }
1954        drawPicture(picture);
1955        restore();
1956    }
1957
1958    /**
1959     * Releases the resources associated with this canvas.
1960     *
1961     * @hide
1962     */
1963    public void release() {
1964        mFinalizer.dispose();
1965    }
1966
1967    /**
1968     * Free up as much memory as possible from private caches (e.g. fonts, images)
1969     *
1970     * @hide
1971     */
1972    public static native void freeCaches();
1973
1974    /**
1975     * Free up text layout caches
1976     *
1977     * @hide
1978     */
1979    public static native void freeTextLayoutCaches();
1980
1981    private static native long initRaster(Bitmap bitmap);
1982    private static native void native_setBitmap(long canvasHandle,
1983                                                Bitmap bitmap);
1984    private static native boolean native_isOpaque(long canvasHandle);
1985    private static native void native_setHighContrastText(long renderer, boolean highContrastText);
1986    private static native int native_getWidth(long canvasHandle);
1987    private static native int native_getHeight(long canvasHandle);
1988
1989    private static native int native_save(long canvasHandle, int saveFlags);
1990    private static native int native_saveLayer(long nativeCanvas, float l,
1991                                               float t, float r, float b,
1992                                               long nativePaint,
1993                                               int layerFlags);
1994    private static native int native_saveLayerAlpha(long nativeCanvas, float l,
1995                                                    float t, float r, float b,
1996                                                    int alpha, int layerFlags);
1997    private static native void native_restore(long canvasHandle, boolean tolerateUnderflow);
1998    private static native void native_restoreToCount(long canvasHandle,
1999                                                     int saveCount,
2000                                                     boolean tolerateUnderflow);
2001    private static native int native_getSaveCount(long canvasHandle);
2002
2003    private static native void native_translate(long canvasHandle,
2004                                                float dx, float dy);
2005    private static native void native_scale(long canvasHandle,
2006                                            float sx, float sy);
2007    private static native void native_rotate(long canvasHandle, float degrees);
2008    private static native void native_skew(long canvasHandle,
2009                                           float sx, float sy);
2010    private static native void native_concat(long nativeCanvas,
2011                                             long nativeMatrix);
2012    private static native void native_setMatrix(long nativeCanvas,
2013                                                long nativeMatrix);
2014    private static native boolean native_clipRect(long nativeCanvas,
2015                                                  float left, float top,
2016                                                  float right, float bottom,
2017                                                  int regionOp);
2018    private static native boolean native_clipPath(long nativeCanvas,
2019                                                  long nativePath,
2020                                                  int regionOp);
2021    private static native boolean native_clipRegion(long nativeCanvas,
2022                                                    long nativeRegion,
2023                                                    int regionOp);
2024    private static native void nativeSetDrawFilter(long nativeCanvas,
2025                                                   long nativeFilter);
2026    private static native boolean native_getClipBounds(long nativeCanvas,
2027                                                       Rect bounds);
2028    private static native void native_getCTM(long nativeCanvas,
2029                                             long nativeMatrix);
2030    private static native boolean native_quickReject(long nativeCanvas,
2031                                                     long nativePath);
2032    private static native boolean native_quickReject(long nativeCanvas,
2033                                                     float left, float top,
2034                                                     float right, float bottom);
2035    private static native void native_drawColor(long nativeCanvas, int color,
2036                                                int mode);
2037    private static native void native_drawPaint(long nativeCanvas,
2038                                                long nativePaint);
2039    private static native void native_drawPoint(long canvasHandle, float x, float y,
2040                                                long paintHandle);
2041    private static native void native_drawPoints(long canvasHandle, float[] pts,
2042                                                 int offset, int count,
2043                                                 long paintHandle);
2044    private static native void native_drawLine(long nativeCanvas, float startX,
2045                                               float startY, float stopX,
2046                                               float stopY, long nativePaint);
2047    private static native void native_drawLines(long canvasHandle, float[] pts,
2048                                                int offset, int count,
2049                                                long paintHandle);
2050    private static native void native_drawRect(long nativeCanvas, float left,
2051                                               float top, float right,
2052                                               float bottom,
2053                                               long nativePaint);
2054    private static native void native_drawOval(long nativeCanvas, float left, float top,
2055                                               float right, float bottom, long nativePaint);
2056    private static native void native_drawCircle(long nativeCanvas, float cx,
2057                                                 float cy, float radius,
2058                                                 long nativePaint);
2059    private static native void native_drawArc(long nativeCanvas, float left, float top,
2060                                              float right, float bottom,
2061                                              float startAngle, float sweep, boolean useCenter,
2062                                              long nativePaint);
2063    private static native void native_drawRoundRect(long nativeCanvas,
2064            float left, float top, float right, float bottom,
2065            float rx, float ry, long nativePaint);
2066    private static native void native_drawPath(long nativeCanvas,
2067                                               long nativePath,
2068                                               long nativePaint);
2069    private static native void native_drawRegion(long nativeCanvas,
2070            long nativeRegion, long nativePaint);
2071    private native void native_drawNinePatch(long nativeCanvas, Bitmap bitmap,
2072            long ninePatch, float dstLeft, float dstTop, float dstRight, float dstBottom,
2073            long nativePaintOrZero, int screenDensity, int bitmapDensity);
2074    private native void native_drawBitmap(long nativeCanvas, Bitmap bitmap,
2075                                                 float left, float top,
2076                                                 long nativePaintOrZero,
2077                                                 int canvasDensity,
2078                                                 int screenDensity,
2079                                                 int bitmapDensity);
2080    private native void native_drawBitmap(long nativeCanvas, Bitmap bitmap,
2081            float srcLeft, float srcTop, float srcRight, float srcBottom,
2082            float dstLeft, float dstTop, float dstRight, float dstBottom,
2083            long nativePaintOrZero, int screenDensity, int bitmapDensity);
2084    private static native void native_drawBitmap(long nativeCanvas, int[] colors,
2085                                                int offset, int stride, float x,
2086                                                 float y, int width, int height,
2087                                                 boolean hasAlpha,
2088                                                 long nativePaintOrZero);
2089    private static native void nativeDrawBitmapMatrix(long nativeCanvas,
2090                                                      Bitmap bitmap,
2091                                                      long nativeMatrix,
2092                                                      long nativePaint);
2093    private static native void nativeDrawBitmapMesh(long nativeCanvas,
2094                                                    Bitmap bitmap,
2095                                                    int meshWidth, int meshHeight,
2096                                                    float[] verts, int vertOffset,
2097                                                    int[] colors, int colorOffset,
2098                                                    long nativePaint);
2099    private static native void nativeDrawVertices(long nativeCanvas, int mode, int n,
2100                   float[] verts, int vertOffset, float[] texs, int texOffset,
2101                   int[] colors, int colorOffset, short[] indices,
2102                   int indexOffset, int indexCount, long nativePaint);
2103
2104    private static native void native_drawText(long nativeCanvas, char[] text,
2105                                               int index, int count, float x,
2106                                               float y, int flags, long nativePaint,
2107                                               long nativeTypeface);
2108    private static native void native_drawText(long nativeCanvas, String text,
2109                                               int start, int end, float x,
2110                                               float y, int flags, long nativePaint,
2111                                               long nativeTypeface);
2112
2113    private static native void native_drawTextRun(long nativeCanvas, String text,
2114            int start, int end, int contextStart, int contextEnd,
2115            float x, float y, boolean isRtl, long nativePaint, long nativeTypeface);
2116
2117    private static native void native_drawTextRun(long nativeCanvas, char[] text,
2118            int start, int count, int contextStart, int contextCount,
2119            float x, float y, boolean isRtl, long nativePaint, long nativeTypeface);
2120
2121    private static native void native_drawTextOnPath(long nativeCanvas,
2122                                                     char[] text, int index,
2123                                                     int count, long nativePath,
2124                                                     float hOffset,
2125                                                     float vOffset, int bidiFlags,
2126                                                     long nativePaint, long nativeTypeface);
2127    private static native void native_drawTextOnPath(long nativeCanvas,
2128                                                     String text, long nativePath,
2129                                                     float hOffset,
2130                                                     float vOffset,
2131                                                     int flags, long nativePaint, long nativeTypeface);
2132    private static native void finalizer(long nativeCanvas);
2133}
2134