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