1
+ package com .nativescript .label ;
2
+ import android .graphics .Canvas ;
3
+ import android .graphics .Paint ;
4
+ import android .graphics .Rect ;
5
+ import android .graphics .drawable .ShapeDrawable ;
6
+ import android .graphics .drawable .shapes .RoundRectShape ;
7
+ import android .graphics .drawable .shapes .Shape ;
8
+ import android .text .style .ReplacementSpan ;
9
+
10
+ public class CustomBackgroundSpan extends ReplacementSpan {
11
+ public static class RoundedRectDrawable extends ShapeDrawable {
12
+ private final Paint fillpaint , strokepaint ;
13
+ public RoundedRectDrawable (int radius , int fillColor , int strokeColor , int strokeWidth ) {
14
+ super (new RoundRectShape (new float [] { radius , radius , radius , radius , radius , radius , radius , radius },
15
+ null , null ));
16
+ fillpaint = new Paint (this .getPaint ());
17
+ fillpaint .setColor (fillColor );
18
+ strokepaint = new Paint (fillpaint );
19
+ strokepaint .setStyle (Paint .Style .STROKE );
20
+ strokepaint .setStrokeWidth (strokeWidth );
21
+ strokepaint .setColor (strokeColor );
22
+ }
23
+
24
+ @ Override
25
+ protected void onDraw (Shape shape , Canvas canvas , Paint paint ) {
26
+ shape .draw (canvas , fillpaint );
27
+ shape .draw (canvas , strokepaint );
28
+ }
29
+ }
30
+ private RoundedRectDrawable mDrawable ;
31
+
32
+ int radius ;
33
+ int fillColor ;
34
+ int strokeColor ;
35
+ int strokeWidth ;
36
+
37
+ public CustomBackgroundSpan (int radius , int fillColor , int strokeColor , int strokeWidth ) {
38
+ this .mDrawable = new RoundedRectDrawable (radius , fillColor , strokeColor , strokeWidth );
39
+ this .radius = radius ;
40
+ this .fillColor = fillColor ;
41
+ this .strokeColor = strokeColor ;
42
+ this .strokeWidth = strokeWidth ;
43
+ }
44
+
45
+ public CustomBackgroundSpan (CustomBackgroundSpan toCopy ) {
46
+ this (toCopy .radius , toCopy .fillColor , toCopy .strokeColor , toCopy .strokeWidth );
47
+ }
48
+
49
+ @ Override
50
+ public int getSize (Paint paint , CharSequence text , int start , int end , Paint .FontMetricsInt fm ) {
51
+ return measureText (paint , text , start , end );
52
+
53
+ }
54
+
55
+ private int measureText (Paint paint , CharSequence text , int start , int end ) {
56
+ return Math .round (paint .measureText (text , start , end ));
57
+ }
58
+
59
+ @ Override
60
+ public void draw (Canvas canvas , CharSequence text , int start , int end , float x , int top , int y , int bottom , Paint paint ) {
61
+ float dx = strokeWidth / 2 ;
62
+ Rect rect = new Rect ((int )(x + dx ), (int )(top + dx ), (int )(x + measureText (paint , text , start , end ) - strokeWidth /2 ), (int )(bottom - strokeWidth /2 ));
63
+ this .mDrawable .setBounds (rect );
64
+ canvas .save ();
65
+ this .mDrawable .draw (canvas );
66
+ canvas .restore ();
67
+ canvas .drawText (text , start , end , x , y , paint );
68
+ }
69
+
70
+ }
0 commit comments