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