Paint.java revision 6d9fe5bd22b531bfce69b146254a4791c76acddc
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.text.GraphicsOperations;
20import android.text.SpannableString;
21import android.text.SpannedString;
22import android.text.TextUtils;
23
24import java.util.Locale;
25
26/**
27 * The Paint class holds the style and color information about how to draw
28 * geometries, text and bitmaps.
29 */
30public class Paint {
31
32    /**
33     * @hide
34     */
35    public int mNativePaint;
36
37    private ColorFilter mColorFilter;
38    private MaskFilter  mMaskFilter;
39    private PathEffect  mPathEffect;
40    private Rasterizer  mRasterizer;
41    private Shader      mShader;
42    private Typeface    mTypeface;
43    private Xfermode    mXfermode;
44
45    private boolean     mHasCompatScaling;
46    private float       mCompatScaling;
47    private float       mInvCompatScaling;
48
49    private Locale      mLocale;
50
51    /**
52     * @hide
53     */
54    public boolean hasShadow;
55    /**
56     * @hide
57     */
58    public float shadowDx;
59    /**
60     * @hide
61     */
62    public float shadowDy;
63    /**
64     * @hide
65     */
66    public float shadowRadius;
67    /**
68     * @hide
69     */
70    public int shadowColor;
71
72    static final Style[] sStyleArray = {
73        Style.FILL, Style.STROKE, Style.FILL_AND_STROKE
74    };
75    static final Cap[] sCapArray = {
76        Cap.BUTT, Cap.ROUND, Cap.SQUARE
77    };
78    static final Join[] sJoinArray = {
79        Join.MITER, Join.ROUND, Join.BEVEL
80    };
81    static final Align[] sAlignArray = {
82        Align.LEFT, Align.CENTER, Align.RIGHT
83    };
84
85    /** bit mask for the flag enabling antialiasing */
86    public static final int ANTI_ALIAS_FLAG     = 0x01;
87    /** bit mask for the flag enabling bitmap filtering */
88    public static final int FILTER_BITMAP_FLAG  = 0x02;
89    /** bit mask for the flag enabling dithering */
90    public static final int DITHER_FLAG         = 0x04;
91    /** bit mask for the flag enabling underline text */
92    public static final int UNDERLINE_TEXT_FLAG = 0x08;
93    /** bit mask for the flag enabling strike-thru text */
94    public static final int STRIKE_THRU_TEXT_FLAG = 0x10;
95    /** bit mask for the flag enabling fake-bold text */
96    public static final int FAKE_BOLD_TEXT_FLAG = 0x20;
97    /** bit mask for the flag enabling linear-text (no caching) */
98    public static final int LINEAR_TEXT_FLAG    = 0x40;
99    /** bit mask for the flag enabling subpixel-text */
100    public static final int SUBPIXEL_TEXT_FLAG  = 0x80;
101    /** bit mask for the flag enabling device kerning for text */
102    public static final int DEV_KERN_TEXT_FLAG  = 0x100;
103
104    // we use this when we first create a paint
105    static final int DEFAULT_PAINT_FLAGS = DEV_KERN_TEXT_FLAG;
106
107    /**
108     * Option for {@link #setHinting}: disable hinting.
109     */
110    public static final int HINTING_OFF = 0x0;
111
112    /**
113     * Option for {@link #setHinting}: enable hinting.
114     */
115    public static final int HINTING_ON = 0x1;
116
117    /**
118     * Option for getTextRunCursor to compute the valid cursor after
119     * offset or the limit of the context, whichever is less.
120     * @hide
121     */
122    public static final int CURSOR_AFTER = 0;
123
124    /**
125     * Option for getTextRunCursor to compute the valid cursor at or after
126     * the offset or the limit of the context, whichever is less.
127     * @hide
128     */
129    public static final int CURSOR_AT_OR_AFTER = 1;
130
131     /**
132     * Option for getTextRunCursor to compute the valid cursor before
133     * offset or the start of the context, whichever is greater.
134     * @hide
135     */
136    public static final int CURSOR_BEFORE = 2;
137
138   /**
139     * Option for getTextRunCursor to compute the valid cursor at or before
140     * offset or the start of the context, whichever is greater.
141     * @hide
142     */
143    public static final int CURSOR_AT_OR_BEFORE = 3;
144
145    /**
146     * Option for getTextRunCursor to return offset if the cursor at offset
147     * is valid, or -1 if it isn't.
148     * @hide
149     */
150    public static final int CURSOR_AT = 4;
151
152    /**
153     * Maximum cursor option value.
154     */
155    private static final int CURSOR_OPT_MAX_VALUE = CURSOR_AT;
156
157    /**
158     * The Style specifies if the primitive being drawn is filled, stroked, or
159     * both (in the same color). The default is FILL.
160     */
161    public enum Style {
162        /**
163         * Geometry and text drawn with this style will be filled, ignoring all
164         * stroke-related settings in the paint.
165         */
166        FILL            (0),
167        /**
168         * Geometry and text drawn with this style will be stroked, respecting
169         * the stroke-related fields on the paint.
170         */
171        STROKE          (1),
172        /**
173         * Geometry and text drawn with this style will be both filled and
174         * stroked at the same time, respecting the stroke-related fields on
175         * the paint. This mode can give unexpected results if the geometry
176         * is oriented counter-clockwise. This restriction does not apply to
177         * either FILL or STROKE.
178         */
179        FILL_AND_STROKE (2);
180
181        Style(int nativeInt) {
182            this.nativeInt = nativeInt;
183        }
184        final int nativeInt;
185    }
186
187    /**
188     * The Cap specifies the treatment for the beginning and ending of
189     * stroked lines and paths. The default is BUTT.
190     */
191    public enum Cap {
192        /**
193         * The stroke ends with the path, and does not project beyond it.
194         */
195        BUTT    (0),
196        /**
197         * The stroke projects out as a semicircle, with the center at the
198         * end of the path.
199         */
200        ROUND   (1),
201        /**
202         * The stroke projects out as a square, with the center at the end
203         * of the path.
204         */
205        SQUARE  (2);
206
207        private Cap(int nativeInt) {
208            this.nativeInt = nativeInt;
209        }
210        final int nativeInt;
211    }
212
213    /**
214     * The Join specifies the treatment where lines and curve segments
215     * join on a stroked path. The default is MITER.
216     */
217    public enum Join {
218        /**
219         * The outer edges of a join meet at a sharp angle
220         */
221        MITER   (0),
222        /**
223         * The outer edges of a join meet in a circular arc.
224         */
225        ROUND   (1),
226        /**
227         * The outer edges of a join meet with a straight line
228         */
229        BEVEL   (2);
230
231        private Join(int nativeInt) {
232            this.nativeInt = nativeInt;
233        }
234        final int nativeInt;
235    }
236
237    /**
238     * Align specifies how drawText aligns its text relative to the
239     * [x,y] coordinates. The default is LEFT.
240     */
241    public enum Align {
242        /**
243         * The text is drawn to the right of the x,y origin
244         */
245        LEFT    (0),
246        /**
247         * The text is drawn centered horizontally on the x,y origin
248         */
249        CENTER  (1),
250        /**
251         * The text is drawn to the left of the x,y origin
252         */
253        RIGHT   (2);
254
255        private Align(int nativeInt) {
256            this.nativeInt = nativeInt;
257        }
258        final int nativeInt;
259    }
260
261    /**
262     * Create a new paint with default settings.
263     */
264    public Paint() {
265        this(0);
266    }
267
268    /**
269     * Create a new paint with the specified flags. Use setFlags() to change
270     * these after the paint is created.
271     *
272     * @param flags initial flag bits, as if they were passed via setFlags().
273     */
274    public Paint(int flags) {
275        mNativePaint = native_init();
276        setFlags(flags | DEFAULT_PAINT_FLAGS);
277        // TODO: Turning off hinting has undesirable side effects, we need to
278        //       revisit hinting once we add support for subpixel positioning
279        // setHinting(DisplayMetrics.DENSITY_DEVICE >= DisplayMetrics.DENSITY_TV
280        //        ? HINTING_OFF : HINTING_ON);
281        mCompatScaling = mInvCompatScaling = 1;
282        setTextLocale(Locale.getDefault());
283    }
284
285    /**
286     * Create a new paint, initialized with the attributes in the specified
287     * paint parameter.
288     *
289     * @param paint Existing paint used to initialized the attributes of the
290     *              new paint.
291     */
292    public Paint(Paint paint) {
293        mNativePaint = native_initWithPaint(paint.mNativePaint);
294        setClassVariablesFrom(paint);
295    }
296
297    /** Restores the paint to its default settings. */
298    public void reset() {
299        native_reset(mNativePaint);
300        setFlags(DEFAULT_PAINT_FLAGS);
301
302        // TODO: Turning off hinting has undesirable side effects, we need to
303        //       revisit hinting once we add support for subpixel positioning
304        // setHinting(DisplayMetrics.DENSITY_DEVICE >= DisplayMetrics.DENSITY_TV
305        //        ? HINTING_OFF : HINTING_ON);
306
307        mColorFilter = null;
308        mMaskFilter = null;
309        mPathEffect = null;
310        mRasterizer = null;
311        mShader = null;
312        mTypeface = null;
313        mXfermode = null;
314
315        mHasCompatScaling = false;
316        mCompatScaling = 1;
317        mInvCompatScaling = 1;
318
319        hasShadow = false;
320        shadowDx = 0;
321        shadowDy = 0;
322        shadowRadius = 0;
323        shadowColor = 0;
324
325        setTextLocale(Locale.getDefault());
326    }
327
328    /**
329     * Copy the fields from src into this paint. This is equivalent to calling
330     * get() on all of the src fields, and calling the corresponding set()
331     * methods on this.
332     */
333    public void set(Paint src) {
334        if (this != src) {
335            // copy over the native settings
336            native_set(mNativePaint, src.mNativePaint);
337            setClassVariablesFrom(src);
338        }
339    }
340
341    /**
342     * Set all class variables using current values from the given
343     * {@link Paint}.
344     */
345    private void setClassVariablesFrom(Paint paint) {
346        mColorFilter = paint.mColorFilter;
347        mMaskFilter = paint.mMaskFilter;
348        mPathEffect = paint.mPathEffect;
349        mRasterizer = paint.mRasterizer;
350        mShader = paint.mShader;
351        mTypeface = paint.mTypeface;
352        mXfermode = paint.mXfermode;
353
354        mHasCompatScaling = paint.mHasCompatScaling;
355        mCompatScaling = paint.mCompatScaling;
356        mInvCompatScaling = paint.mInvCompatScaling;
357
358        hasShadow = paint.hasShadow;
359        shadowDx = paint.shadowDx;
360        shadowDy = paint.shadowDy;
361        shadowRadius = paint.shadowRadius;
362        shadowColor = paint.shadowColor;
363
364        mLocale = paint.mLocale;
365    }
366
367    /** @hide */
368    public void setCompatibilityScaling(float factor) {
369        if (factor == 1.0) {
370            mHasCompatScaling = false;
371            mCompatScaling = mInvCompatScaling = 1.0f;
372        } else {
373            mHasCompatScaling = true;
374            mCompatScaling = factor;
375            mInvCompatScaling = 1.0f/factor;
376        }
377    }
378
379    /**
380     * Return the paint's flags. Use the Flag enum to test flag values.
381     *
382     * @return the paint's flags (see enums ending in _Flag for bit masks)
383     */
384    public native int getFlags();
385
386    /**
387     * Set the paint's flags. Use the Flag enum to specific flag values.
388     *
389     * @param flags The new flag bits for the paint
390     */
391    public native void setFlags(int flags);
392
393    /**
394     * Return the paint's hinting mode.  Returns either
395     * {@link #HINTING_OFF} or {@link #HINTING_ON}.
396     */
397    public native int getHinting();
398
399    /**
400     * Set the paint's hinting mode.  May be either
401     * {@link #HINTING_OFF} or {@link #HINTING_ON}.
402     */
403    public native void setHinting(int mode);
404
405    /**
406     * Helper for getFlags(), returning true if ANTI_ALIAS_FLAG bit is set
407     * AntiAliasing smooths out the edges of what is being drawn, but is has
408     * no impact on the interior of the shape. See setDither() and
409     * setFilterBitmap() to affect how colors are treated.
410     *
411     * @return true if the antialias bit is set in the paint's flags.
412     */
413    public final boolean isAntiAlias() {
414        return (getFlags() & ANTI_ALIAS_FLAG) != 0;
415    }
416
417    /**
418     * Helper for setFlags(), setting or clearing the ANTI_ALIAS_FLAG bit
419     * AntiAliasing smooths out the edges of what is being drawn, but is has
420     * no impact on the interior of the shape. See setDither() and
421     * setFilterBitmap() to affect how colors are treated.
422     *
423     * @param aa true to set the antialias bit in the flags, false to clear it
424     */
425    public native void setAntiAlias(boolean aa);
426
427    /**
428     * Helper for getFlags(), returning true if DITHER_FLAG bit is set
429     * Dithering affects how colors that are higher precision than the device
430     * are down-sampled. No dithering is generally faster, but higher precision
431     * colors are just truncated down (e.g. 8888 -> 565). Dithering tries to
432     * distribute the error inherent in this process, to reduce the visual
433     * artifacts.
434     *
435     * @return true if the dithering bit is set in the paint's flags.
436     */
437    public final boolean isDither() {
438        return (getFlags() & DITHER_FLAG) != 0;
439    }
440
441    /**
442     * Helper for setFlags(), setting or clearing the DITHER_FLAG bit
443     * Dithering affects how colors that are higher precision than the device
444     * are down-sampled. No dithering is generally faster, but higher precision
445     * colors are just truncated down (e.g. 8888 -> 565). Dithering tries to
446     * distribute the error inherent in this process, to reduce the visual
447     * artifacts.
448     *
449     * @param dither true to set the dithering bit in flags, false to clear it
450     */
451    public native void setDither(boolean dither);
452
453    /**
454     * Helper for getFlags(), returning true if LINEAR_TEXT_FLAG bit is set
455     *
456     * @return true if the lineartext bit is set in the paint's flags
457     */
458    public final boolean isLinearText() {
459        return (getFlags() & LINEAR_TEXT_FLAG) != 0;
460    }
461
462    /**
463     * Helper for setFlags(), setting or clearing the LINEAR_TEXT_FLAG bit
464     *
465     * @param linearText true to set the linearText bit in the paint's flags,
466     *                   false to clear it.
467     */
468    public native void setLinearText(boolean linearText);
469
470    /**
471     * Helper for getFlags(), returning true if SUBPIXEL_TEXT_FLAG bit is set
472     *
473     * @return true if the subpixel bit is set in the paint's flags
474     */
475    public final boolean isSubpixelText() {
476        return (getFlags() & SUBPIXEL_TEXT_FLAG) != 0;
477    }
478
479    /**
480     * Helper for setFlags(), setting or clearing the SUBPIXEL_TEXT_FLAG bit
481     *
482     * @param subpixelText true to set the subpixelText bit in the paint's
483     *                     flags, false to clear it.
484     */
485    public native void setSubpixelText(boolean subpixelText);
486
487    /**
488     * Helper for getFlags(), returning true if UNDERLINE_TEXT_FLAG bit is set
489     *
490     * @return true if the underlineText bit is set in the paint's flags.
491     */
492    public final boolean isUnderlineText() {
493        return (getFlags() & UNDERLINE_TEXT_FLAG) != 0;
494    }
495
496    /**
497     * Helper for setFlags(), setting or clearing the UNDERLINE_TEXT_FLAG bit
498     *
499     * @param underlineText true to set the underlineText bit in the paint's
500     *                      flags, false to clear it.
501     */
502    public native void setUnderlineText(boolean underlineText);
503
504    /**
505     * Helper for getFlags(), returning true if STRIKE_THRU_TEXT_FLAG bit is set
506     *
507     * @return true if the strikeThruText bit is set in the paint's flags.
508     */
509    public final boolean isStrikeThruText() {
510        return (getFlags() & STRIKE_THRU_TEXT_FLAG) != 0;
511    }
512
513    /**
514     * Helper for setFlags(), setting or clearing the STRIKE_THRU_TEXT_FLAG bit
515     *
516     * @param strikeThruText true to set the strikeThruText bit in the paint's
517     *                       flags, false to clear it.
518     */
519    public native void setStrikeThruText(boolean strikeThruText);
520
521    /**
522     * Helper for getFlags(), returning true if FAKE_BOLD_TEXT_FLAG bit is set
523     *
524     * @return true if the fakeBoldText bit is set in the paint's flags.
525     */
526    public final boolean isFakeBoldText() {
527        return (getFlags() & FAKE_BOLD_TEXT_FLAG) != 0;
528    }
529
530    /**
531     * Helper for setFlags(), setting or clearing the FAKE_BOLD_TEXT_FLAG bit
532     *
533     * @param fakeBoldText true to set the fakeBoldText bit in the paint's
534     *                     flags, false to clear it.
535     */
536    public native void setFakeBoldText(boolean fakeBoldText);
537
538    /**
539     * Whether or not the bitmap filter is activated.
540     * Filtering affects the sampling of bitmaps when they are transformed.
541     * Filtering does not affect how the colors in the bitmap are converted into
542     * device pixels. That is dependent on dithering and xfermodes.
543     *
544     * @see #setFilterBitmap(boolean) setFilterBitmap()
545     */
546    public final boolean isFilterBitmap() {
547        return (getFlags() & FILTER_BITMAP_FLAG) != 0;
548    }
549
550    /**
551     * Helper for setFlags(), setting or clearing the FILTER_BITMAP_FLAG bit.
552     * Filtering affects the sampling of bitmaps when they are transformed.
553     * Filtering does not affect how the colors in the bitmap are converted into
554     * device pixels. That is dependent on dithering and xfermodes.
555     *
556     * @param filter true to set the FILTER_BITMAP_FLAG bit in the paint's
557     *               flags, false to clear it.
558     */
559    public native void setFilterBitmap(boolean filter);
560
561    /**
562     * Return the paint's style, used for controlling how primitives'
563     * geometries are interpreted (except for drawBitmap, which always assumes
564     * FILL_STYLE).
565     *
566     * @return the paint's style setting (Fill, Stroke, StrokeAndFill)
567     */
568    public Style getStyle() {
569        return sStyleArray[native_getStyle(mNativePaint)];
570    }
571
572    /**
573     * Set the paint's style, used for controlling how primitives'
574     * geometries are interpreted (except for drawBitmap, which always assumes
575     * Fill).
576     *
577     * @param style The new style to set in the paint
578     */
579    public void setStyle(Style style) {
580        native_setStyle(mNativePaint, style.nativeInt);
581    }
582
583    /**
584     * Return the paint's color. Note that the color is a 32bit value
585     * containing alpha as well as r,g,b. This 32bit value is not premultiplied,
586     * meaning that its alpha can be any value, regardless of the values of
587     * r,g,b. See the Color class for more details.
588     *
589     * @return the paint's color (and alpha).
590     */
591    public native int getColor();
592
593    /**
594     * Set the paint's color. Note that the color is an int containing alpha
595     * as well as r,g,b. This 32bit value is not premultiplied, meaning that
596     * its alpha can be any value, regardless of the values of r,g,b.
597     * See the Color class for more details.
598     *
599     * @param color The new color (including alpha) to set in the paint.
600     */
601    public native void setColor(int color);
602
603    /**
604     * Helper to getColor() that just returns the color's alpha value. This is
605     * the same as calling getColor() >>> 24. It always returns a value between
606     * 0 (completely transparent) and 255 (completely opaque).
607     *
608     * @return the alpha component of the paint's color.
609     */
610    public native int getAlpha();
611
612    /**
613     * Helper to setColor(), that only assigns the color's alpha value,
614     * leaving its r,g,b values unchanged. Results are undefined if the alpha
615     * value is outside of the range [0..255]
616     *
617     * @param a set the alpha component [0..255] of the paint's color.
618     */
619    public native void setAlpha(int a);
620
621    /**
622     * Helper to setColor(), that takes a,r,g,b and constructs the color int
623     *
624     * @param a The new alpha component (0..255) of the paint's color.
625     * @param r The new red component (0..255) of the paint's color.
626     * @param g The new green component (0..255) of the paint's color.
627     * @param b The new blue component (0..255) of the paint's color.
628     */
629    public void setARGB(int a, int r, int g, int b) {
630        setColor((a << 24) | (r << 16) | (g << 8) | b);
631    }
632
633    /**
634     * Return the width for stroking.
635     * <p />
636     * A value of 0 strokes in hairline mode.
637     * Hairlines always draws a single pixel independent of the canva's matrix.
638     *
639     * @return the paint's stroke width, used whenever the paint's style is
640     *         Stroke or StrokeAndFill.
641     */
642    public native float getStrokeWidth();
643
644    /**
645     * Set the width for stroking.
646     * Pass 0 to stroke in hairline mode.
647     * Hairlines always draws a single pixel independent of the canva's matrix.
648     *
649     * @param width set the paint's stroke width, used whenever the paint's
650     *              style is Stroke or StrokeAndFill.
651     */
652    public native void setStrokeWidth(float width);
653
654    /**
655     * Return the paint's stroke miter value. Used to control the behavior
656     * of miter joins when the joins angle is sharp.
657     *
658     * @return the paint's miter limit, used whenever the paint's style is
659     *         Stroke or StrokeAndFill.
660     */
661    public native float getStrokeMiter();
662
663    /**
664     * Set the paint's stroke miter value. This is used to control the behavior
665     * of miter joins when the joins angle is sharp. This value must be >= 0.
666     *
667     * @param miter set the miter limit on the paint, used whenever the paint's
668     *              style is Stroke or StrokeAndFill.
669     */
670    public native void setStrokeMiter(float miter);
671
672    /**
673     * Return the paint's Cap, controlling how the start and end of stroked
674     * lines and paths are treated.
675     *
676     * @return the line cap style for the paint, used whenever the paint's
677     *         style is Stroke or StrokeAndFill.
678     */
679    public Cap getStrokeCap() {
680        return sCapArray[native_getStrokeCap(mNativePaint)];
681    }
682
683    /**
684     * Set the paint's Cap.
685     *
686     * @param cap set the paint's line cap style, used whenever the paint's
687     *            style is Stroke or StrokeAndFill.
688     */
689    public void setStrokeCap(Cap cap) {
690        native_setStrokeCap(mNativePaint, cap.nativeInt);
691    }
692
693    /**
694     * Return the paint's stroke join type.
695     *
696     * @return the paint's Join.
697     */
698    public Join getStrokeJoin() {
699        return sJoinArray[native_getStrokeJoin(mNativePaint)];
700    }
701
702    /**
703     * Set the paint's Join.
704     *
705     * @param join set the paint's Join, used whenever the paint's style is
706     *             Stroke or StrokeAndFill.
707     */
708    public void setStrokeJoin(Join join) {
709        native_setStrokeJoin(mNativePaint, join.nativeInt);
710    }
711
712    /**
713     * Applies any/all effects (patheffect, stroking) to src, returning the
714     * result in dst. The result is that drawing src with this paint will be
715     * the same as drawing dst with a default paint (at least from the
716     * geometric perspective).
717     *
718     * @param src input path
719     * @param dst output path (may be the same as src)
720     * @return    true if the path should be filled, or false if it should be
721     *                 drawn with a hairline (width == 0)
722     */
723    public boolean getFillPath(Path src, Path dst) {
724        return native_getFillPath(mNativePaint, src.ni(), dst.ni());
725    }
726
727    /**
728     * Get the paint's shader object.
729     *
730     * @return the paint's shader (or null)
731     */
732    public Shader getShader() {
733        return mShader;
734    }
735
736    /**
737     * Set or clear the shader object.
738     * <p />
739     * Pass null to clear any previous shader.
740     * As a convenience, the parameter passed is also returned.
741     *
742     * @param shader May be null. the new shader to be installed in the paint
743     * @return       shader
744     */
745    public Shader setShader(Shader shader) {
746        int shaderNative = 0;
747        if (shader != null)
748            shaderNative = shader.native_instance;
749        native_setShader(mNativePaint, shaderNative);
750        mShader = shader;
751        return shader;
752    }
753
754    /**
755     * Get the paint's colorfilter (maybe be null).
756     *
757     * @return the paint's colorfilter (maybe be null)
758     */
759    public ColorFilter getColorFilter() {
760        return mColorFilter;
761    }
762
763    /**
764     * Set or clear the paint's colorfilter, returning the parameter.
765     *
766     * @param filter May be null. The new filter to be installed in the paint
767     * @return       filter
768     */
769    public ColorFilter setColorFilter(ColorFilter filter) {
770        int filterNative = 0;
771        if (filter != null)
772            filterNative = filter.native_instance;
773        native_setColorFilter(mNativePaint, filterNative);
774        mColorFilter = filter;
775        return filter;
776    }
777
778    /**
779     * Get the paint's xfermode object.
780     *
781     * @return the paint's xfermode (or null)
782     */
783    public Xfermode getXfermode() {
784        return mXfermode;
785    }
786
787    /**
788     * Set or clear the xfermode object.
789     * <p />
790     * Pass null to clear any previous xfermode.
791     * As a convenience, the parameter passed is also returned.
792     *
793     * @param xfermode May be null. The xfermode to be installed in the paint
794     * @return         xfermode
795     */
796    public Xfermode setXfermode(Xfermode xfermode) {
797        int xfermodeNative = 0;
798        if (xfermode != null)
799            xfermodeNative = xfermode.native_instance;
800        native_setXfermode(mNativePaint, xfermodeNative);
801        mXfermode = xfermode;
802        return xfermode;
803    }
804
805    /**
806     * Get the paint's patheffect object.
807     *
808     * @return the paint's patheffect (or null)
809     */
810    public PathEffect getPathEffect() {
811        return mPathEffect;
812    }
813
814    /**
815     * Set or clear the patheffect object.
816     * <p />
817     * Pass null to clear any previous patheffect.
818     * As a convenience, the parameter passed is also returned.
819     *
820     * @param effect May be null. The patheffect to be installed in the paint
821     * @return       effect
822     */
823    public PathEffect setPathEffect(PathEffect effect) {
824        int effectNative = 0;
825        if (effect != null) {
826            effectNative = effect.native_instance;
827        }
828        native_setPathEffect(mNativePaint, effectNative);
829        mPathEffect = effect;
830        return effect;
831    }
832
833    /**
834     * Get the paint's maskfilter object.
835     *
836     * @return the paint's maskfilter (or null)
837     */
838    public MaskFilter getMaskFilter() {
839        return mMaskFilter;
840    }
841
842    /**
843     * Set or clear the maskfilter object.
844     * <p />
845     * Pass null to clear any previous maskfilter.
846     * As a convenience, the parameter passed is also returned.
847     *
848     * @param maskfilter May be null. The maskfilter to be installed in the
849     *                   paint
850     * @return           maskfilter
851     */
852    public MaskFilter setMaskFilter(MaskFilter maskfilter) {
853        int maskfilterNative = 0;
854        if (maskfilter != null) {
855            maskfilterNative = maskfilter.native_instance;
856        }
857        native_setMaskFilter(mNativePaint, maskfilterNative);
858        mMaskFilter = maskfilter;
859        return maskfilter;
860    }
861
862    /**
863     * Get the paint's typeface object.
864     * <p />
865     * The typeface object identifies which font to use when drawing or
866     * measuring text.
867     *
868     * @return the paint's typeface (or null)
869     */
870    public Typeface getTypeface() {
871        return mTypeface;
872    }
873
874    /**
875     * Set or clear the typeface object.
876     * <p />
877     * Pass null to clear any previous typeface.
878     * As a convenience, the parameter passed is also returned.
879     *
880     * @param typeface May be null. The typeface to be installed in the paint
881     * @return         typeface
882     */
883    public Typeface setTypeface(Typeface typeface) {
884        int typefaceNative = 0;
885        if (typeface != null) {
886            typefaceNative = typeface.native_instance;
887        }
888        native_setTypeface(mNativePaint, typefaceNative);
889        mTypeface = typeface;
890        return typeface;
891    }
892
893    /**
894     * Get the paint's rasterizer (or null).
895     * <p />
896     * The raster controls/modifies how paths/text are turned into alpha masks.
897     *
898     * @return         the paint's rasterizer (or null)
899     */
900    public Rasterizer getRasterizer() {
901        return mRasterizer;
902    }
903
904    /**
905     * Set or clear the rasterizer object.
906     * <p />
907     * Pass null to clear any previous rasterizer.
908     * As a convenience, the parameter passed is also returned.
909     *
910     * @param rasterizer May be null. The new rasterizer to be installed in
911     *                   the paint.
912     * @return           rasterizer
913     */
914    public Rasterizer setRasterizer(Rasterizer rasterizer) {
915        int rasterizerNative = 0;
916        if (rasterizer != null) {
917            rasterizerNative = rasterizer.native_instance;
918        }
919        native_setRasterizer(mNativePaint, rasterizerNative);
920        mRasterizer = rasterizer;
921        return rasterizer;
922    }
923
924    /**
925     * This draws a shadow layer below the main layer, with the specified
926     * offset and color, and blur radius. If radius is 0, then the shadow
927     * layer is removed.
928     */
929    public void setShadowLayer(float radius, float dx, float dy, int color) {
930        hasShadow = radius > 0.0f;
931        shadowRadius = radius;
932        shadowDx = dx;
933        shadowDy = dy;
934        shadowColor = color;
935        nSetShadowLayer(radius, dx, dy, color);
936    }
937
938    private native void nSetShadowLayer(float radius, float dx, float dy, int color);
939
940    /**
941     * Clear the shadow layer.
942     */
943    public void clearShadowLayer() {
944        hasShadow = false;
945        nSetShadowLayer(0, 0, 0, 0);
946    }
947
948    /**
949     * Return the paint's Align value for drawing text. This controls how the
950     * text is positioned relative to its origin. LEFT align means that all of
951     * the text will be drawn to the right of its origin (i.e. the origin
952     * specifieds the LEFT edge of the text) and so on.
953     *
954     * @return the paint's Align value for drawing text.
955     */
956    public Align getTextAlign() {
957        return sAlignArray[native_getTextAlign(mNativePaint)];
958    }
959
960    /**
961     * Set the paint's text alignment. This controls how the
962     * text is positioned relative to its origin. LEFT align means that all of
963     * the text will be drawn to the right of its origin (i.e. the origin
964     * specifieds the LEFT edge of the text) and so on.
965     *
966     * @param align set the paint's Align value for drawing text.
967     */
968    public void setTextAlign(Align align) {
969        native_setTextAlign(mNativePaint, align.nativeInt);
970    }
971
972    /**
973     * Get the text Locale.
974     *
975     * @return the paint's Locale used for drawing text, never null.
976     */
977    public Locale getTextLocale() {
978        return mLocale;
979    }
980
981    /**
982     * Set the text locale.
983     *
984     * The text locale affects how the text is drawn for some languages.
985     *
986     * For example, if the locale is {@link Locale#CHINESE} or {@link Locale#CHINA},
987     * then the text renderer will prefer to draw text using a Chinese font. Likewise,
988     * if the locale is {@link Locale#JAPANESE} or {@link Locale#JAPAN}, then the text
989     * renderer will prefer to draw text using a Japanese font.
990     *
991     * This distinction is important because Chinese and Japanese text both use many
992     * of the same Unicode code points but their appearance is subtly different for
993     * each language.
994     *
995     * By default, the text locale is initialized to the system locale (as returned
996     * by {@link Locale#getDefault}). This assumes that the text to be rendered will
997     * most likely be in the user's preferred language.
998     *
999     * If the actual language of the text is known, then it can be provided to the
1000     * text renderer using this method. The text renderer may attempt to guess the
1001     * language script based on the contents of the text to be drawn independent of
1002     * the text locale here. Specifying the text locale just helps it do a better
1003     * job in certain ambiguous cases
1004     *
1005     * @param locale the paint's locale value for drawing text, must not be null.
1006     */
1007    public void setTextLocale(Locale locale) {
1008        if (locale == null) {
1009            throw new IllegalArgumentException("locale cannot be null");
1010        }
1011        if (locale.equals(mLocale)) return;
1012        mLocale = locale;
1013        native_setTextLocale(mNativePaint, locale.toString());
1014    }
1015
1016    /**
1017     * Return the paint's text size.
1018     *
1019     * @return the paint's text size.
1020     */
1021    public native float getTextSize();
1022
1023    /**
1024     * Set the paint's text size. This value must be > 0
1025     *
1026     * @param textSize set the paint's text size.
1027     */
1028    public native void setTextSize(float textSize);
1029
1030    /**
1031     * Return the paint's horizontal scale factor for text. The default value
1032     * is 1.0.
1033     *
1034     * @return the paint's scale factor in X for drawing/measuring text
1035     */
1036    public native float getTextScaleX();
1037
1038    /**
1039     * Set the paint's horizontal scale factor for text. The default value
1040     * is 1.0. Values > 1.0 will stretch the text wider. Values < 1.0 will
1041     * stretch the text narrower.
1042     *
1043     * @param scaleX set the paint's scale in X for drawing/measuring text.
1044     */
1045    public native void setTextScaleX(float scaleX);
1046
1047    /**
1048     * Return the paint's horizontal skew factor for text. The default value
1049     * is 0.
1050     *
1051     * @return         the paint's skew factor in X for drawing text.
1052     */
1053    public native float getTextSkewX();
1054
1055    /**
1056     * Set the paint's horizontal skew factor for text. The default value
1057     * is 0. For approximating oblique text, use values around -0.25.
1058     *
1059     * @param skewX set the paint's skew factor in X for drawing text.
1060     */
1061    public native void setTextSkewX(float skewX);
1062
1063    /**
1064     * Return the distance above (negative) the baseline (ascent) based on the
1065     * current typeface and text size.
1066     *
1067     * @return the distance above (negative) the baseline (ascent) based on the
1068     *         current typeface and text size.
1069     */
1070    public native float ascent();
1071
1072    /**
1073     * Return the distance below (positive) the baseline (descent) based on the
1074     * current typeface and text size.
1075     *
1076     * @return the distance below (positive) the baseline (descent) based on
1077     *         the current typeface and text size.
1078     */
1079    public native float descent();
1080
1081    /**
1082     * Class that describes the various metrics for a font at a given text size.
1083     * Remember, Y values increase going down, so those values will be positive,
1084     * and values that measure distances going up will be negative. This class
1085     * is returned by getFontMetrics().
1086     */
1087    public static class FontMetrics {
1088        /**
1089         * The maximum distance above the baseline for the tallest glyph in
1090         * the font at a given text size.
1091         */
1092        public float   top;
1093        /**
1094         * The recommended distance above the baseline for singled spaced text.
1095         */
1096        public float   ascent;
1097        /**
1098         * The recommended distance below the baseline for singled spaced text.
1099         */
1100        public float   descent;
1101        /**
1102         * The maximum distance below the baseline for the lowest glyph in
1103         * the font at a given text size.
1104         */
1105        public float   bottom;
1106        /**
1107         * The recommended additional space to add between lines of text.
1108         */
1109        public float   leading;
1110    }
1111
1112    /**
1113     * Return the font's recommended interline spacing, given the Paint's
1114     * settings for typeface, textSize, etc. If metrics is not null, return the
1115     * fontmetric values in it.
1116     *
1117     * @param metrics If this object is not null, its fields are filled with
1118     *                the appropriate values given the paint's text attributes.
1119     * @return the font's recommended interline spacing.
1120     */
1121    public native float getFontMetrics(FontMetrics metrics);
1122
1123    /**
1124     * Allocates a new FontMetrics object, and then calls getFontMetrics(fm)
1125     * with it, returning the object.
1126     */
1127    public FontMetrics getFontMetrics() {
1128        FontMetrics fm = new FontMetrics();
1129        getFontMetrics(fm);
1130        return fm;
1131    }
1132
1133    /**
1134     * Convenience method for callers that want to have FontMetrics values as
1135     * integers.
1136     */
1137    public static class FontMetricsInt {
1138        public int   top;
1139        public int   ascent;
1140        public int   descent;
1141        public int   bottom;
1142        public int   leading;
1143
1144        @Override public String toString() {
1145            return "FontMetricsInt: top=" + top + " ascent=" + ascent +
1146                    " descent=" + descent + " bottom=" + bottom +
1147                    " leading=" + leading;
1148        }
1149    }
1150
1151    /**
1152     * Return the font's interline spacing, given the Paint's settings for
1153     * typeface, textSize, etc. If metrics is not null, return the fontmetric
1154     * values in it. Note: all values have been converted to integers from
1155     * floats, in such a way has to make the answers useful for both spacing
1156     * and clipping. If you want more control over the rounding, call
1157     * getFontMetrics().
1158     *
1159     * @return the font's interline spacing.
1160     */
1161    public native int getFontMetricsInt(FontMetricsInt fmi);
1162
1163    public FontMetricsInt getFontMetricsInt() {
1164        FontMetricsInt fm = new FontMetricsInt();
1165        getFontMetricsInt(fm);
1166        return fm;
1167    }
1168
1169    /**
1170     * Return the recommend line spacing based on the current typeface and
1171     * text size.
1172     *
1173     * @return  recommend line spacing based on the current typeface and
1174     *          text size.
1175     */
1176    public float getFontSpacing() {
1177        return getFontMetrics(null);
1178    }
1179
1180    /**
1181     * Return the width of the text.
1182     *
1183     * @param text  The text to measure. Cannot be null.
1184     * @param index The index of the first character to start measuring
1185     * @param count THe number of characters to measure, beginning with start
1186     * @return      The width of the text
1187     */
1188    public float measureText(char[] text, int index, int count) {
1189        if (text == null) {
1190            throw new IllegalArgumentException("text cannot be null");
1191        }
1192        if ((index | count) < 0 || index + count > text.length) {
1193            throw new ArrayIndexOutOfBoundsException();
1194        }
1195
1196        if (text.length == 0 || count == 0) {
1197            return 0f;
1198        }
1199        if (!mHasCompatScaling) {
1200            return native_measureText(text, index, count);
1201        }
1202
1203        final float oldSize = getTextSize();
1204        setTextSize(oldSize*mCompatScaling);
1205        float w = native_measureText(text, index, count);
1206        setTextSize(oldSize);
1207        return w*mInvCompatScaling;
1208    }
1209
1210    private native float native_measureText(char[] text, int index, int count);
1211
1212    /**
1213     * Return the width of the text.
1214     *
1215     * @param text  The text to measure. Cannot be null.
1216     * @param start The index of the first character to start measuring
1217     * @param end   1 beyond the index of the last character to measure
1218     * @return      The width of the text
1219     */
1220    public float measureText(String text, int start, int end) {
1221        if (text == null) {
1222            throw new IllegalArgumentException("text cannot be null");
1223        }
1224        if ((start | end | (end - start) | (text.length() - end)) < 0) {
1225            throw new IndexOutOfBoundsException();
1226        }
1227
1228        if (text.length() == 0 || start == end) {
1229            return 0f;
1230        }
1231        if (!mHasCompatScaling) {
1232            return native_measureText(text, start, end);
1233        }
1234
1235        final float oldSize = getTextSize();
1236        setTextSize(oldSize*mCompatScaling);
1237        float w = native_measureText(text, start, end);
1238        setTextSize(oldSize);
1239        return w*mInvCompatScaling;
1240    }
1241
1242    private native float native_measureText(String text, int start, int end);
1243
1244    /**
1245     * Return the width of the text.
1246     *
1247     * @param text  The text to measure. Cannot be null.
1248     * @return      The width of the text
1249     */
1250    public float measureText(String text) {
1251        if (text == null) {
1252            throw new IllegalArgumentException("text cannot be null");
1253        }
1254
1255        if (text.length() == 0) {
1256            return 0f;
1257        }
1258
1259        if (!mHasCompatScaling) return native_measureText(text);
1260        final float oldSize = getTextSize();
1261        setTextSize(oldSize*mCompatScaling);
1262        float w = native_measureText(text);
1263        setTextSize(oldSize);
1264        return w*mInvCompatScaling;
1265    }
1266
1267    private native float native_measureText(String text);
1268
1269    /**
1270     * Return the width of the text.
1271     *
1272     * @param text  The text to measure
1273     * @param start The index of the first character to start measuring
1274     * @param end   1 beyond the index of the last character to measure
1275     * @return      The width of the text
1276     */
1277    public float measureText(CharSequence text, int start, int end) {
1278        if (text == null) {
1279            throw new IllegalArgumentException("text cannot be null");
1280        }
1281        if ((start | end | (end - start) | (text.length() - end)) < 0) {
1282            throw new IndexOutOfBoundsException();
1283        }
1284
1285        if (text.length() == 0 || start == end) {
1286            return 0f;
1287        }
1288        if (text instanceof String) {
1289            return measureText((String)text, start, end);
1290        }
1291        if (text instanceof SpannedString ||
1292            text instanceof SpannableString) {
1293            return measureText(text.toString(), start, end);
1294        }
1295        if (text instanceof GraphicsOperations) {
1296            return ((GraphicsOperations)text).measureText(start, end, this);
1297        }
1298
1299        char[] buf = TemporaryBuffer.obtain(end - start);
1300        TextUtils.getChars(text, start, end, buf, 0);
1301        float result = measureText(buf, 0, end - start);
1302        TemporaryBuffer.recycle(buf);
1303        return result;
1304    }
1305
1306    /**
1307     * Measure the text, stopping early if the measured width exceeds maxWidth.
1308     * Return the number of chars that were measured, and if measuredWidth is
1309     * not null, return in it the actual width measured.
1310     *
1311     * @param text  The text to measure. Cannot be null.
1312     * @param index The offset into text to begin measuring at
1313     * @param count The number of maximum number of entries to measure. If count
1314     *              is negative, then the characters are measured in reverse order.
1315     * @param maxWidth The maximum width to accumulate.
1316     * @param measuredWidth Optional. If not null, returns the actual width
1317     *                     measured.
1318     * @return The number of chars that were measured. Will always be <=
1319     *         abs(count).
1320     */
1321    public int breakText(char[] text, int index, int count,
1322                                float maxWidth, float[] measuredWidth) {
1323        if (text == null) {
1324            throw new IllegalArgumentException("text cannot be null");
1325        }
1326        if (index < 0 || text.length - index < Math.abs(count)) {
1327            throw new ArrayIndexOutOfBoundsException();
1328        }
1329
1330        if (text.length == 0 || count == 0) {
1331            return 0;
1332        }
1333        if (!mHasCompatScaling) {
1334            return native_breakText(text, index, count, maxWidth, measuredWidth);
1335        }
1336
1337        final float oldSize = getTextSize();
1338        setTextSize(oldSize*mCompatScaling);
1339        int res = native_breakText(text, index, count, maxWidth*mCompatScaling,
1340                measuredWidth);
1341        setTextSize(oldSize);
1342        if (measuredWidth != null) measuredWidth[0] *= mInvCompatScaling;
1343        return res;
1344    }
1345
1346    private native int native_breakText(char[] text, int index, int count,
1347                                        float maxWidth, float[] measuredWidth);
1348
1349    /**
1350     * Measure the text, stopping early if the measured width exceeds maxWidth.
1351     * Return the number of chars that were measured, and if measuredWidth is
1352     * not null, return in it the actual width measured.
1353     *
1354     * @param text  The text to measure. Cannot be null.
1355     * @param start The offset into text to begin measuring at
1356     * @param end   The end of the text slice to measure.
1357     * @param measureForwards If true, measure forwards, starting at start.
1358     *                        Otherwise, measure backwards, starting with end.
1359     * @param maxWidth The maximum width to accumulate.
1360     * @param measuredWidth Optional. If not null, returns the actual width
1361     *                     measured.
1362     * @return The number of chars that were measured. Will always be <=
1363     *         abs(end - start).
1364     */
1365    public int breakText(CharSequence text, int start, int end,
1366                         boolean measureForwards,
1367                         float maxWidth, float[] measuredWidth) {
1368        if (text == null) {
1369            throw new IllegalArgumentException("text cannot be null");
1370        }
1371        if ((start | end | (end - start) | (text.length() - end)) < 0) {
1372            throw new IndexOutOfBoundsException();
1373        }
1374
1375        if (text.length() == 0 || start == end) {
1376            return 0;
1377        }
1378        if (start == 0 && text instanceof String && end == text.length()) {
1379            return breakText((String) text, measureForwards, maxWidth,
1380                             measuredWidth);
1381        }
1382
1383        char[] buf = TemporaryBuffer.obtain(end - start);
1384        int result;
1385
1386        TextUtils.getChars(text, start, end, buf, 0);
1387
1388        if (measureForwards) {
1389            result = breakText(buf, 0, end - start, maxWidth, measuredWidth);
1390        } else {
1391            result = breakText(buf, 0, -(end - start), maxWidth, measuredWidth);
1392        }
1393
1394        TemporaryBuffer.recycle(buf);
1395        return result;
1396    }
1397
1398    /**
1399     * Measure the text, stopping early if the measured width exceeds maxWidth.
1400     * Return the number of chars that were measured, and if measuredWidth is
1401     * not null, return in it the actual width measured.
1402     *
1403     * @param text  The text to measure. Cannot be null.
1404     * @param measureForwards If true, measure forwards, starting with the
1405     *                        first character in the string. Otherwise,
1406     *                        measure backwards, starting with the
1407     *                        last character in the string.
1408     * @param maxWidth The maximum width to accumulate.
1409     * @param measuredWidth Optional. If not null, returns the actual width
1410     *                     measured.
1411     * @return The number of chars that were measured. Will always be <=
1412     *         abs(count).
1413     */
1414    public int breakText(String text, boolean measureForwards,
1415                                float maxWidth, float[] measuredWidth) {
1416        if (text == null) {
1417            throw new IllegalArgumentException("text cannot be null");
1418        }
1419
1420        if (text.length() == 0) {
1421            return 0;
1422        }
1423        if (!mHasCompatScaling) {
1424            return native_breakText(text, measureForwards, maxWidth, measuredWidth);
1425        }
1426
1427        final float oldSize = getTextSize();
1428        setTextSize(oldSize*mCompatScaling);
1429        int res = native_breakText(text, measureForwards, maxWidth*mCompatScaling,
1430                measuredWidth);
1431        setTextSize(oldSize);
1432        if (measuredWidth != null) measuredWidth[0] *= mInvCompatScaling;
1433        return res;
1434    }
1435
1436    private native int native_breakText(String text, boolean measureForwards,
1437                                        float maxWidth, float[] measuredWidth);
1438
1439    /**
1440     * Return the advance widths for the characters in the string.
1441     *
1442     * @param text     The text to measure. Cannot be null.
1443     * @param index    The index of the first char to to measure
1444     * @param count    The number of chars starting with index to measure
1445     * @param widths   array to receive the advance widths of the characters.
1446     *                 Must be at least a large as count.
1447     * @return         the actual number of widths returned.
1448     */
1449    public int getTextWidths(char[] text, int index, int count,
1450                             float[] widths) {
1451        if (text == null) {
1452            throw new IllegalArgumentException("text cannot be null");
1453        }
1454        if ((index | count) < 0 || index + count > text.length
1455                || count > widths.length) {
1456            throw new ArrayIndexOutOfBoundsException();
1457        }
1458
1459        if (text.length == 0 || count == 0) {
1460            return 0;
1461        }
1462        if (!mHasCompatScaling) {
1463            return native_getTextWidths(mNativePaint, text, index, count, widths);
1464        }
1465
1466        final float oldSize = getTextSize();
1467        setTextSize(oldSize*mCompatScaling);
1468        int res = native_getTextWidths(mNativePaint, text, index, count, widths);
1469        setTextSize(oldSize);
1470        for (int i=0; i<res; i++) {
1471            widths[i] *= mInvCompatScaling;
1472        }
1473        return res;
1474    }
1475
1476    /**
1477     * Return the advance widths for the characters in the string.
1478     *
1479     * @param text     The text to measure. Cannot be null.
1480     * @param start    The index of the first char to to measure
1481     * @param end      The end of the text slice to measure
1482     * @param widths   array to receive the advance widths of the characters.
1483     *                 Must be at least a large as (end - start).
1484     * @return         the actual number of widths returned.
1485     */
1486    public int getTextWidths(CharSequence text, int start, int end,
1487                             float[] widths) {
1488        if (text == null) {
1489            throw new IllegalArgumentException("text cannot be null");
1490        }
1491        if ((start | end | (end - start) | (text.length() - end)) < 0) {
1492            throw new IndexOutOfBoundsException();
1493        }
1494        if (end - start > widths.length) {
1495            throw new ArrayIndexOutOfBoundsException();
1496        }
1497
1498        if (text.length() == 0 || start == end) {
1499            return 0;
1500        }
1501        if (text instanceof String) {
1502            return getTextWidths((String) text, start, end, widths);
1503        }
1504        if (text instanceof SpannedString ||
1505            text instanceof SpannableString) {
1506            return getTextWidths(text.toString(), start, end, widths);
1507        }
1508        if (text instanceof GraphicsOperations) {
1509            return ((GraphicsOperations) text).getTextWidths(start, end,
1510                                                                 widths, this);
1511        }
1512
1513        char[] buf = TemporaryBuffer.obtain(end - start);
1514        TextUtils.getChars(text, start, end, buf, 0);
1515        int result = getTextWidths(buf, 0, end - start, widths);
1516        TemporaryBuffer.recycle(buf);
1517        return result;
1518    }
1519
1520    /**
1521     * Return the advance widths for the characters in the string.
1522     *
1523     * @param text   The text to measure. Cannot be null.
1524     * @param start  The index of the first char to to measure
1525     * @param end    The end of the text slice to measure
1526     * @param widths array to receive the advance widths of the characters.
1527     *               Must be at least a large as the text.
1528     * @return       the number of unichars in the specified text.
1529     */
1530    public int getTextWidths(String text, int start, int end, float[] widths) {
1531        if (text == null) {
1532            throw new IllegalArgumentException("text cannot be null");
1533        }
1534        if ((start | end | (end - start) | (text.length() - end)) < 0) {
1535            throw new IndexOutOfBoundsException();
1536        }
1537        if (end - start > widths.length) {
1538            throw new ArrayIndexOutOfBoundsException();
1539        }
1540
1541        if (text.length() == 0 || start == end) {
1542            return 0;
1543        }
1544        if (!mHasCompatScaling) {
1545            return native_getTextWidths(mNativePaint, text, start, end, widths);
1546        }
1547
1548        final float oldSize = getTextSize();
1549        setTextSize(oldSize*mCompatScaling);
1550        int res = native_getTextWidths(mNativePaint, text, start, end, widths);
1551        setTextSize(oldSize);
1552        for (int i=0; i<res; i++) {
1553            widths[i] *= mInvCompatScaling;
1554        }
1555        return res;
1556    }
1557
1558    /**
1559     * Return the advance widths for the characters in the string.
1560     *
1561     * @param text   The text to measure
1562     * @param widths array to receive the advance widths of the characters.
1563     *               Must be at least a large as the text.
1564     * @return       the number of unichars in the specified text.
1565     */
1566    public int getTextWidths(String text, float[] widths) {
1567        return getTextWidths(text, 0, text.length(), widths);
1568    }
1569
1570    /**
1571     * Convenience overload that takes a char array instead of a
1572     * String.
1573     *
1574     * @see #getTextRunAdvances(String, int, int, int, int, float[], int)
1575     * @hide
1576     */
1577    public float getTextRunAdvances(char[] chars, int index, int count,
1578            int contextIndex, int contextCount, float[] advances,
1579            int advancesIndex) {
1580
1581        if (chars == null) {
1582            throw new IllegalArgumentException("text cannot be null");
1583        }
1584        if ((index | count | contextIndex | contextCount | advancesIndex
1585                | (index - contextIndex) | (contextCount - count)
1586                | ((contextIndex + contextCount) - (index + count))
1587                | (chars.length - (contextIndex + contextCount))
1588                | (advances == null ? 0 :
1589                    (advances.length - (advancesIndex + count)))) < 0) {
1590            throw new IndexOutOfBoundsException();
1591        }
1592
1593        if (chars.length == 0 || count == 0){
1594            return 0f;
1595        }
1596        if (!mHasCompatScaling) {
1597            return native_getTextRunAdvances(mNativePaint, chars, index, count,
1598                    contextIndex, contextCount, advances, advancesIndex);
1599        }
1600
1601        final float oldSize = getTextSize();
1602        setTextSize(oldSize * mCompatScaling);
1603        float res = native_getTextRunAdvances(mNativePaint, chars, index, count,
1604                contextIndex, contextCount, advances, advancesIndex);
1605        setTextSize(oldSize);
1606
1607        if (advances != null) {
1608            for (int i = advancesIndex, e = i + count; i < e; i++) {
1609                advances[i] *= mInvCompatScaling;
1610            }
1611        }
1612        return res * mInvCompatScaling; // assume errors are not significant
1613    }
1614
1615    /**
1616     * Convenience overload that takes a CharSequence instead of a
1617     * String.
1618     *
1619     * @see #getTextRunAdvances(String, int, int, int, int, float[], int)
1620     * @hide
1621     */
1622    public float getTextRunAdvances(CharSequence text, int start, int end,
1623            int contextStart, int contextEnd, float[] advances,
1624            int advancesIndex) {
1625
1626        if (text == null) {
1627            throw new IllegalArgumentException("text cannot be null");
1628        }
1629        if ((start | end | contextStart | contextEnd | advancesIndex | (end - start)
1630                | (start - contextStart) | (contextEnd - end)
1631                | (text.length() - contextEnd)
1632                | (advances == null ? 0 :
1633                    (advances.length - advancesIndex - (end - start)))) < 0) {
1634            throw new IndexOutOfBoundsException();
1635        }
1636
1637        if (text instanceof String) {
1638            return getTextRunAdvances((String) text, start, end,
1639                    contextStart, contextEnd, advances, advancesIndex);
1640        }
1641        if (text instanceof SpannedString ||
1642            text instanceof SpannableString) {
1643            return getTextRunAdvances(text.toString(), start, end,
1644                    contextStart, contextEnd, advances, advancesIndex);
1645        }
1646        if (text instanceof GraphicsOperations) {
1647            return ((GraphicsOperations) text).getTextRunAdvances(start, end,
1648                    contextStart, contextEnd, advances, advancesIndex, this);
1649        }
1650        if (text.length() == 0 || end == start) {
1651            return 0f;
1652        }
1653
1654        int contextLen = contextEnd - contextStart;
1655        int len = end - start;
1656        char[] buf = TemporaryBuffer.obtain(contextLen);
1657        TextUtils.getChars(text, contextStart, contextEnd, buf, 0);
1658        float result = getTextRunAdvances(buf, start - contextStart, len,
1659                0, contextLen, advances, advancesIndex);
1660        TemporaryBuffer.recycle(buf);
1661        return result;
1662    }
1663
1664    /**
1665     * Returns the total advance width for the characters in the run
1666     * between start and end, and if advances is not null, the advance
1667     * assigned to each of these characters (java chars).
1668     *
1669     * <p>The trailing surrogate in a valid surrogate pair is assigned
1670     * an advance of 0.  Thus the number of returned advances is
1671     * always equal to count, not to the number of unicode codepoints
1672     * represented by the run.
1673     *
1674     * <p>In the case of conjuncts or combining marks, the total
1675     * advance is assigned to the first logical character, and the
1676     * following characters are assigned an advance of 0.
1677     *
1678     * <p>This generates the sum of the advances of glyphs for
1679     * characters in a reordered cluster as the width of the first
1680     * logical character in the cluster, and 0 for the widths of all
1681     * other characters in the cluster.  In effect, such clusters are
1682     * treated like conjuncts.
1683     *
1684     * <p>The shaping bounds limit the amount of context available
1685     * outside start and end that can be used for shaping analysis.
1686     * These bounds typically reflect changes in bidi level or font
1687     * metrics across which shaping does not occur.
1688     *
1689     * @param text the text to measure. Cannot be null.
1690     * @param start the index of the first character to measure
1691     * @param end the index past the last character to measure
1692     * @param contextStart the index of the first character to use for shaping context,
1693     * must be <= start
1694     * @param contextEnd the index past the last character to use for shaping context,
1695     * must be >= end
1696     * @param advances array to receive the advances, must have room for all advances,
1697     * can be null if only total advance is needed
1698     * @param advancesIndex the position in advances at which to put the
1699     * advance corresponding to the character at start
1700     * @return the total advance
1701     *
1702     * @hide
1703     */
1704    public float getTextRunAdvances(String text, int start, int end, int contextStart,
1705            int contextEnd, float[] advances, int advancesIndex) {
1706
1707        if (text == null) {
1708            throw new IllegalArgumentException("text cannot be null");
1709        }
1710        if ((start | end | contextStart | contextEnd | advancesIndex | (end - start)
1711                | (start - contextStart) | (contextEnd - end)
1712                | (text.length() - contextEnd)
1713                | (advances == null ? 0 :
1714                    (advances.length - advancesIndex - (end - start)))) < 0) {
1715            throw new IndexOutOfBoundsException();
1716        }
1717
1718        if (text.length() == 0 || start == end) {
1719            return 0f;
1720        }
1721
1722        if (!mHasCompatScaling) {
1723            return native_getTextRunAdvances(mNativePaint, text, start, end,
1724                    contextStart, contextEnd, advances, advancesIndex);
1725        }
1726
1727        final float oldSize = getTextSize();
1728        setTextSize(oldSize * mCompatScaling);
1729        float totalAdvance = native_getTextRunAdvances(mNativePaint, text, start, end,
1730                contextStart, contextEnd, advances, advancesIndex);
1731        setTextSize(oldSize);
1732
1733        if (advances != null) {
1734            for (int i = advancesIndex, e = i + (end - start); i < e; i++) {
1735                advances[i] *= mInvCompatScaling;
1736            }
1737        }
1738        return totalAdvance * mInvCompatScaling; // assume errors are insignificant
1739    }
1740
1741    /**
1742     * Returns the next cursor position in the run.  This avoids placing the
1743     * cursor between surrogates, between characters that form conjuncts,
1744     * between base characters and combining marks, or within a reordering
1745     * cluster.
1746     *
1747     * <p>ContextStart and offset are relative to the start of text.
1748     * The context is the shaping context for cursor movement, generally
1749     * the bounds of the metric span enclosing the cursor in the direction of
1750     * movement.
1751     *
1752     * <p>If cursorOpt is {@link #CURSOR_AT} and the offset is not a valid
1753     * cursor position, this returns -1.  Otherwise this will never return a
1754     * value before contextStart or after contextStart + contextLength.
1755     *
1756     * @param text the text
1757     * @param contextStart the start of the context
1758     * @param contextLength the length of the context
1759     * @param offset the cursor position to move from
1760     * @param cursorOpt how to move the cursor, one of {@link #CURSOR_AFTER},
1761     * {@link #CURSOR_AT_OR_AFTER}, {@link #CURSOR_BEFORE},
1762     * {@link #CURSOR_AT_OR_BEFORE}, or {@link #CURSOR_AT}
1763     * @return the offset of the next position, or -1
1764     * @hide
1765     */
1766    public int getTextRunCursor(char[] text, int contextStart, int contextLength,
1767            int offset, int cursorOpt) {
1768        int contextEnd = contextStart + contextLength;
1769        if (((contextStart | contextEnd | offset | (contextEnd - contextStart)
1770                | (offset - contextStart) | (contextEnd - offset)
1771                | (text.length - contextEnd) | cursorOpt) < 0)
1772                || cursorOpt > CURSOR_OPT_MAX_VALUE) {
1773            throw new IndexOutOfBoundsException();
1774        }
1775
1776        return native_getTextRunCursor(mNativePaint, text,
1777                contextStart, contextLength, offset, cursorOpt);
1778    }
1779
1780    /**
1781     * Returns the next cursor position in the run.  This avoids placing the
1782     * cursor between surrogates, between characters that form conjuncts,
1783     * between base characters and combining marks, or within a reordering
1784     * cluster.
1785     *
1786     * <p>ContextStart, contextEnd, and offset are relative to the start of
1787     * text.  The context is the shaping context for cursor movement, generally
1788     * the bounds of the metric span enclosing the cursor in the direction of
1789     * movement.
1790     *
1791     * <p>If cursorOpt is {@link #CURSOR_AT} and the offset is not a valid
1792     * cursor position, this returns -1.  Otherwise this will never return a
1793     * value before contextStart or after contextEnd.
1794     *
1795     * @param text the text
1796     * @param contextStart the start of the context
1797     * @param contextEnd the end of the context
1798     * @param offset the cursor position to move from
1799     * @param cursorOpt how to move the cursor, one of {@link #CURSOR_AFTER},
1800     * {@link #CURSOR_AT_OR_AFTER}, {@link #CURSOR_BEFORE},
1801     * {@link #CURSOR_AT_OR_BEFORE}, or {@link #CURSOR_AT}
1802     * @return the offset of the next position, or -1
1803     * @hide
1804     */
1805    public int getTextRunCursor(CharSequence text, int contextStart,
1806           int contextEnd, int offset, int cursorOpt) {
1807
1808        if (text instanceof String || text instanceof SpannedString ||
1809                text instanceof SpannableString) {
1810            return getTextRunCursor(text.toString(), contextStart, contextEnd,
1811                    offset, cursorOpt);
1812        }
1813        if (text instanceof GraphicsOperations) {
1814            return ((GraphicsOperations) text).getTextRunCursor(
1815                    contextStart, contextEnd, offset, cursorOpt, this);
1816        }
1817
1818        int contextLen = contextEnd - contextStart;
1819        char[] buf = TemporaryBuffer.obtain(contextLen);
1820        TextUtils.getChars(text, contextStart, contextEnd, buf, 0);
1821        int result = getTextRunCursor(buf, 0, contextLen, offset - contextStart, cursorOpt);
1822        TemporaryBuffer.recycle(buf);
1823        return result;
1824    }
1825
1826    /**
1827     * Returns the next cursor position in the run.  This avoids placing the
1828     * cursor between surrogates, between characters that form conjuncts,
1829     * between base characters and combining marks, or within a reordering
1830     * cluster.
1831     *
1832     * <p>ContextStart, contextEnd, and offset are relative to the start of
1833     * text.  The context is the shaping context for cursor movement, generally
1834     * the bounds of the metric span enclosing the cursor in the direction of
1835     * movement.
1836     *
1837     * <p>If cursorOpt is {@link #CURSOR_AT} and the offset is not a valid
1838     * cursor position, this returns -1.  Otherwise this will never return a
1839     * value before contextStart or after contextEnd.
1840     *
1841     * @param text the text
1842     * @param contextStart the start of the context
1843     * @param contextEnd the end of the context
1844     * @param offset the cursor position to move from
1845     * @param cursorOpt how to move the cursor, one of {@link #CURSOR_AFTER},
1846     * {@link #CURSOR_AT_OR_AFTER}, {@link #CURSOR_BEFORE},
1847     * {@link #CURSOR_AT_OR_BEFORE}, or {@link #CURSOR_AT}
1848     * @return the offset of the next position, or -1
1849     * @hide
1850     */
1851    public int getTextRunCursor(String text, int contextStart, int contextEnd,
1852            int flags, int offset, int cursorOpt) {
1853        if (((contextStart | contextEnd | offset | (contextEnd - contextStart)
1854                | (offset - contextStart) | (contextEnd - offset)
1855                | (text.length() - contextEnd) | cursorOpt) < 0)
1856                || cursorOpt > CURSOR_OPT_MAX_VALUE) {
1857            throw new IndexOutOfBoundsException();
1858        }
1859
1860        return native_getTextRunCursor(mNativePaint, text,
1861                contextStart, contextEnd, offset, cursorOpt);
1862    }
1863
1864    /**
1865     * Return the path (outline) for the specified text.
1866     * Note: just like Canvas.drawText, this will respect the Align setting in
1867     * the paint.
1868     *
1869     * @param text     The text to retrieve the path from
1870     * @param index    The index of the first character in text
1871     * @param count    The number of characterss starting with index
1872     * @param x        The x coordinate of the text's origin
1873     * @param y        The y coordinate of the text's origin
1874     * @param path     The path to receive the data describing the text. Must
1875     *                 be allocated by the caller.
1876     */
1877    public void getTextPath(char[] text, int index, int count,
1878                            float x, float y, Path path) {
1879        if ((index | count) < 0 || index + count > text.length) {
1880            throw new ArrayIndexOutOfBoundsException();
1881        }
1882        native_getTextPath(mNativePaint, text, index, count, x, y,
1883                path.ni());
1884    }
1885
1886    /**
1887     * Return the path (outline) for the specified text.
1888     * Note: just like Canvas.drawText, this will respect the Align setting
1889     * in the paint.
1890     *
1891     * @param text  The text to retrieve the path from
1892     * @param start The first character in the text
1893     * @param end   1 past the last charcter in the text
1894     * @param x     The x coordinate of the text's origin
1895     * @param y     The y coordinate of the text's origin
1896     * @param path  The path to receive the data describing the text. Must
1897     *              be allocated by the caller.
1898     */
1899    public void getTextPath(String text, int start, int end,
1900                            float x, float y, Path path) {
1901        if ((start | end | (end - start) | (text.length() - end)) < 0) {
1902            throw new IndexOutOfBoundsException();
1903        }
1904        native_getTextPath(mNativePaint, text, start, end, x, y,
1905                path.ni());
1906    }
1907
1908    /**
1909     * Return in bounds (allocated by the caller) the smallest rectangle that
1910     * encloses all of the characters, with an implied origin at (0,0).
1911     *
1912     * @param text  String to measure and return its bounds
1913     * @param start Index of the first char in the string to measure
1914     * @param end   1 past the last char in the string measure
1915     * @param bounds Returns the unioned bounds of all the text. Must be
1916     *               allocated by the caller.
1917     */
1918    public void getTextBounds(String text, int start, int end, Rect bounds) {
1919        if ((start | end | (end - start) | (text.length() - end)) < 0) {
1920            throw new IndexOutOfBoundsException();
1921        }
1922        if (bounds == null) {
1923            throw new NullPointerException("need bounds Rect");
1924        }
1925        nativeGetStringBounds(mNativePaint, text, start, end, bounds);
1926    }
1927
1928    /**
1929     * Return in bounds (allocated by the caller) the smallest rectangle that
1930     * encloses all of the characters, with an implied origin at (0,0).
1931     *
1932     * @param text  Array of chars to measure and return their unioned bounds
1933     * @param index Index of the first char in the array to measure
1934     * @param count The number of chars, beginning at index, to measure
1935     * @param bounds Returns the unioned bounds of all the text. Must be
1936     *               allocated by the caller.
1937     */
1938    public void getTextBounds(char[] text, int index, int count, Rect bounds) {
1939        if ((index | count) < 0 || index + count > text.length) {
1940            throw new ArrayIndexOutOfBoundsException();
1941        }
1942        if (bounds == null) {
1943            throw new NullPointerException("need bounds Rect");
1944        }
1945        nativeGetCharArrayBounds(mNativePaint, text, index, count, bounds);
1946    }
1947
1948    @Override
1949    protected void finalize() throws Throwable {
1950        try {
1951            finalizer(mNativePaint);
1952        } finally {
1953            super.finalize();
1954        }
1955    }
1956
1957    private static native int native_init();
1958    private static native int native_initWithPaint(int paint);
1959    private static native void native_reset(int native_object);
1960    private static native void native_set(int native_dst, int native_src);
1961    private static native int native_getStyle(int native_object);
1962    private static native void native_setStyle(int native_object, int style);
1963    private static native int native_getStrokeCap(int native_object);
1964    private static native void native_setStrokeCap(int native_object, int cap);
1965    private static native int native_getStrokeJoin(int native_object);
1966    private static native void native_setStrokeJoin(int native_object,
1967                                                    int join);
1968    private static native boolean native_getFillPath(int native_object,
1969                                                     int src, int dst);
1970    private static native int native_setShader(int native_object, int shader);
1971    private static native int native_setColorFilter(int native_object,
1972                                                    int filter);
1973    private static native int native_setXfermode(int native_object,
1974                                                 int xfermode);
1975    private static native int native_setPathEffect(int native_object,
1976                                                   int effect);
1977    private static native int native_setMaskFilter(int native_object,
1978                                                   int maskfilter);
1979    private static native int native_setTypeface(int native_object,
1980                                                 int typeface);
1981    private static native int native_setRasterizer(int native_object,
1982                                                   int rasterizer);
1983
1984    private static native int native_getTextAlign(int native_object);
1985    private static native void native_setTextAlign(int native_object,
1986                                                   int align);
1987
1988    private static native void native_setTextLocale(int native_object,
1989                                                    String locale);
1990
1991    private static native int native_getTextWidths(int native_object,
1992                            char[] text, int index, int count, float[] widths);
1993    private static native int native_getTextWidths(int native_object,
1994                            String text, int start, int end, float[] widths);
1995
1996    private static native float native_getTextRunAdvances(int native_object,
1997            char[] text, int index, int count, int contextIndex, int contextCount,
1998            float[] advances, int advancesIndex);
1999    private static native float native_getTextRunAdvances(int native_object,
2000            String text, int start, int end, int contextStart, int contextEnd,
2001            float[] advances, int advancesIndex);
2002
2003    private native int native_getTextRunCursor(int native_object, char[] text,
2004            int contextStart, int contextLength, int offset, int cursorOpt);
2005    private native int native_getTextRunCursor(int native_object, String text,
2006            int contextStart, int contextEnd, int offset, int cursorOpt);
2007
2008    private static native void native_getTextPath(int native_object, char[] text,
2009            int index, int count, float x, float y, int path);
2010    private static native void native_getTextPath(int native_object, String text,
2011            int start, int end, float x, float y, int path);
2012    private static native void nativeGetStringBounds(int nativePaint,
2013                                String text, int start, int end, Rect bounds);
2014    private static native void nativeGetCharArrayBounds(int nativePaint,
2015                                char[] text, int index, int count, Rect bounds);
2016    private static native void finalizer(int nativePaint);
2017}
2018