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