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