日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

高级UI-画笔Paint

發布時間:2024/4/17 编程问答 40 豆豆
生活随笔 收集整理的這篇文章主要介紹了 高级UI-画笔Paint 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

在UI這一塊,談到自定義,就離不開畫筆和畫布的使用話題,在自定義控件的時候,為了做出炫酷的效果,我們往往會使用畫筆和畫布,那么這里我們就先來看看畫筆的使用吧

簡單使用例子

自定義一個View

public class PaintView extends View {private Paint mPaint;public PaintView(Context context, @Nullable AttributeSet attrs) {super(context, attrs);mPaint = new Paint();}@Overrideprotected void onDraw(Canvas canvas) {super.onDraw(canvas);//重置mPaint.reset();//畫筆設置mPaint.setColor(Color.RED);mPaint.setAlpha(255);//樣式設置 // mPaint.setStyle(Paint.Style.FILL);//填充mPaint.setStyle(Paint.Style.STROKE);//描邊 // mPaint.setStyle(Paint.Style.FILL_AND_STROKE);//填充及描邊//畫筆寬度設置mPaint.setStrokeWidth(20);//線帽設置mPaint.setStrokeCap(Paint.Cap.BUTT);//無 // mPaint.setStrokeCap(Paint.Cap.ROUND);//圓形 // mPaint.setStrokeCap(Paint.Cap.SQUARE);//方形//線條交叉處 // mPaint.setStrokeJoin(Paint.Join.BEVEL);//直角 // mPaint.setStrokeJoin(Paint.Join.ROUND);//圓角 // mPaint.setStrokeJoin(Paint.Join.MITER);//銳角Path path = new Path();path.moveTo(100,100);path.lineTo(300,100);path.lineTo(500,300);mPaint.setStrokeJoin(Paint.Join.BEVEL);canvas.drawPath(path,mPaint);path.moveTo(100,400);path.lineTo(300,400);path.lineTo(500,700);mPaint.setStrokeJoin(Paint.Join.MITER);canvas.drawPath(path,mPaint);path.moveTo(100,800);path.lineTo(300,800);path.lineTo(500,1100);mPaint.setStrokeJoin(Paint.Join.ROUND);canvas.drawPath(path,mPaint);} }

畫了三條線

Paint的使用說明

Paint在是使用的時候,一般會有兩個類參與,一個負責圖形繪制,一個負責文字繪制
在使用前一般重置Paint,調用reset()
設置方法一般都對應著獲取方法

圖形繪制相關方法

  • 設置顏色
mPaint.setColor(Color.RED);
  • 設置透明度0~255
mPaint.setAlpha(255);
  • 設置畫筆的樣式
mPaint.setStyle(Paint.Style.FILL);//填充 //mPaint.setStyle(Paint.Style.STROKE);//描邊 //mPaint.setStyle(Paint.Style.FILL_AND_STROKE);//填充及描邊
  • 設置畫筆的寬度
mPaint.setStrokeWidth(50);
  • 設置線帽
mPaint.setStrokeCap(Paint.Cap.BUTT);//無 //mPaint.setStrokeCap(Paint.Cap.ROUND);//圓形 //mPaint.setStrokeCap(Paint.Cap.SQUARE);//方形
  • 設置線條交叉處樣式
mPaint.setStrokeJoin(Paint.Join.BEVEL);//直角 //mPaint.setStrokeJoin(Paint.Join.ROUND);//圓角 //mPaint.setStrokeJoin(Paint.Join.MITER);//銳角
  • 設置防鋸齒
mPaint.setAntiAlias(true);
  • 設置圖像抖動處理
mPaint.setDither(true);

文字繪制相關方法

  • 設置字符行間距
mPaint.setFontSpacing(5);
  • 設置字符之間的間距
mPaint.getLetterSpacing(5);
  • 設置文本刪除線
mPaint.setStrikeThruText(true);
  • 設置下劃線
mPaint.setUnderlineText(true);
  • 設置文本大小
mPaint.setTextSize(textSize);
  • 設置字體類型
mPaint.setTypeface(Typeface.BOLD);
  • 加載自定義字體
Typeface.create(familyName, style);
  • 設置文字傾斜,默認0,官方推薦的-0.25f是斜體
mPaint.setTextSkewX(-0.25f);
  • 設置文本對齊方式
mPaint.setTextAlign(Align.LEFT); mPaint.setTextAlign(Align.CENTER); mPaint.setTextAlign(Align.RIGHT);
  • 計算制定長度的字符串(字符長度、字符個數、顯示的時候真實的長度)
int breadText = mPaint.breakText(text, measureForwards, maxWidth, measuredWidth);
  • 獲取文本的矩形區域(寬高)Rect bounds
mPaint.getTextBounds(text, index, count, bounds) mPaint.getTextBounds(text, start, end, bounds)
  • 獲取文本的寬度,比較粗略
float measureText = mPaint.measureText(str);
  • 獲取文本的寬度,比較精準
int textWidths = mPaint.getTextWidths(str, measuredWidth);

文本的基線問題

在繪制文本的時候,事宜基準線為準的,但有時我們在繪制的時候又不以基準線穩準,那么就需要通過計算去獲得位置了

canvas.drawText(x,y)這個y并不是text的左上角,而是以baseline為基準的
通過獲得相對于基準線的位置,從而計算出需要的位置,負值表示在基準線上方,正值表示在基準線下方

FontMetrics fontMetrics = mPaint.getFontMetrics(); fontMetrics.top; fontMetrics.ascent; fontMetrics.descent; fontMetrics.bottom;

自定義ProgressBar實現

定義自定義屬性

<?xml version="1.0" encoding="utf-8"?> <resources><declare-styleable name="CustomProgressBar"><attr name="roundProgressColor" format="color" /><attr name="roundColor" format="color" /><attr name="roundWidth" format="dimension" /><attr name="textSize" format="dimension" /><attr name="textColor" format="color" /><attr name="max" format="integer" /><attr name="min" format="integer" /><attr name="textShow" format="boolean" /><attr name="style"><enum name="STROKE" value="0" /><enum name="FILL" value="1" /></attr></declare-styleable> </resources>

自定義ProgressBar

public class CustomProgressBar extends View {public static final int STROKE = 0;public static final int FILL = 1;private int min;private int roundColor;private int roundProgressColor;private float roundWidth;private int style;private int textColor;private boolean textShow;private float textSize;private Paint paint;private int max;private int progress;public CustomProgressBar(Context context, @Nullable AttributeSet attrs) {super(context, attrs);//定義畫筆paint = new Paint();//獲得自定義屬性TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.CustomProgressBar);max = typedArray.getInteger(R.styleable.CustomProgressBar_max, 100);min = typedArray.getInteger(R.styleable.CustomProgressBar_min, 80);roundColor = typedArray.getColor(R.styleable.CustomProgressBar_roundColor, Color.RED);roundProgressColor = typedArray.getColor(R.styleable.CustomProgressBar_roundProgressColor, Color.GRAY);roundWidth = typedArray.getDimension(R.styleable.CustomProgressBar_roundWidth, 10);style = typedArray.getInt(R.styleable.CustomProgressBar_style, 0);textColor = typedArray.getColor(R.styleable.CustomProgressBar_textColor, Color.GREEN);textShow = typedArray.getBoolean(R.styleable.CustomProgressBar_textShow, true);textSize = typedArray.getDimension(R.styleable.CustomProgressBar_textSize, 15);typedArray.recycle();}@Overrideprotected void onDraw(Canvas canvas) {super.onDraw(canvas);//畫默認的外層圓環int center = getWidth() / 2;float radius = center - roundWidth / 2;paint.setColor(roundColor);paint.setStyle(Paint.Style.STROKE);paint.setStrokeWidth(roundWidth);paint.setAntiAlias(true);canvas.drawCircle(center, center, radius, paint);//畫進度百分比paint.setColor(textColor);paint.setStrokeWidth(0);paint.setTextSize(textSize);paint.setTypeface(Typeface.DEFAULT_BOLD);int precent = (int) (progress / (float) max * 100);if (textShow && style == STROKE) {canvas.drawText(precent + "%", (getWidth() - paint.measureText(precent + "%s")) / 2F,(getHeight() - (paint.descent() + paint.ascent())) / 2F, paint);}//畫圓弧paint.setColor(roundProgressColor);paint.setStrokeWidth(roundWidth);RectF oval = new RectF(center - radius, center - radius, center + radius, center + radius);switch (style) {case STROKE:paint.setStyle(Paint.Style.STROKE);canvas.drawArc(oval, 0, 360 * precent / 100, false, paint);break;case FILL:paint.setStyle(Paint.Style.FILL_AND_STROKE);canvas.drawArc(oval, 0, 360 * precent / 100, true, paint);break;}}public int getMin() {return min;}public void setMin(int min) {this.min = min;}public synchronized int getMax() {return max;}public synchronized void setMax(int max) {if (max < 0) {throw new IllegalArgumentException("max不能小于0");}this.max = max;}public synchronized int getProgress() {return progress;}public synchronized void setProgress(int progress) {if (progress < 0) {throw new IllegalArgumentException("progress不能小于0");}if (progress > max) {progress = max;}if (progress <= max) {this.progress = progress;//更新postInvalidate();}}public int getRoundColor() {return roundColor;}public void setRoundColor(int roundColor) {this.roundColor = roundColor;}public int getRoundProgressColor() {return roundProgressColor;}public void setRoundProgressColor(int roundProgressColor) {this.roundProgressColor = roundProgressColor;}public float getRoundWidth() {return roundWidth;}public void setRoundWidth(float roundWidth) {this.roundWidth = roundWidth;}public int getStyle() {return style;}public void setStyle(int style) {this.style = style;}public int getTextColor() {return textColor;}public void setTextColor(int textColor) {this.textColor = textColor;}public boolean isTextShow() {return textShow;}public void setTextShow(boolean textShow) {this.textShow = textShow;}public float getTextSize() {return textSize;}public void setTextSize(float textSize) {this.textSize = textSize;} }

編寫布局

<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:myApp="http://schemas.android.com/apk/res-auto"android:layout_width="match_parent"android:layout_height="match_parent"><com.cj5785.painttest.CustomProgressBarandroid:id="@+id/custom_progress_bar"android:layout_centerInParent="true"android:layout_width="100dp"android:layout_height="100dp"myApp:roundProgressColor="@android:color/holo_green_light"myApp:roundColor="@android:color/holo_blue_light"myApp:roundWidth="10dp"myApp:textColor="@android:color/holo_orange_light"myApp:textSize="18sp" /><Buttonandroid:layout_alignParentBottom="true"android:layout_width="match_parent"android:layout_height="wrap_content"android:onClick="start"/></RelativeLayout>

測試

public class ProgressBarActivity extends AppCompatActivity {private CustomProgressBar progressBar;private int progess;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_progress_bar);progressBar = findViewById(R.id.custom_progress_bar);}public void start(View view) {progess += 5;progressBar.setProgress(progess);} }

效果如下

附錄 API

public class Paint extends Object
java.lang.Object
? ?android.graphics.Paint

The Paint class holds the style and color information about how to draw geometries, text and bitmaps.

Nested classes
enumPaint.Align Align specifies how drawText aligns its text relative to the [x,y] coordinates.
enumPaint.Cap The Cap specifies the treatment for the beginning and ending of stroked lines and paths.
classPaint.FontMetrics Class that describes the various metrics for a font at a given text size.
classPaint.FontMetricsInt Convenience method for callers that want to have FontMetrics values as integers.
enumPaint.Join The Join specifies the treatment where lines and curve segments join on a stroked path.
enumPaint.Style The Style specifies if the primitive being drawn is filled, stroked, or both (in the same color).
Constants
intANTI_ALIAS_FLAG Paint flag that enables antialiasing when drawing.
intDEV_KERN_TEXT_FLAG Legacy Paint flag, no longer used.
intDITHER_FLAG Paint flag that enables dithering when blitting.
intEMBEDDED_BITMAP_TEXT_FLAG Paint flag that enables the use of bitmap fonts when drawing text.
intFAKE_BOLD_TEXT_FLAGPaint flag that applies a synthetic bolding effect to drawn text.
intFILTER_BITMAP_FLAG Paint flag that enables bilinear sampling on scaled bitmaps.
intHINTING_OFF Font hinter option that disables font hinting.
intHINTING_ON Font hinter option that enables font hinting.
intLINEAR_TEXT_FLAG Paint flag that enables smooth linear scaling of text.
intSTRIKE_THRU_TEXT_FLAG Paint flag that applies a strike-through decoration to drawn text.
intSUBPIXEL_TEXT_FLAG Paint flag that enables subpixel positioning of text.
intUNDERLINE_TEXT_FLAG Paint flag that applies an underline decoration to drawn text.
Public constructors
Paint() Create a new paint with default settings.
Paint(int flags) Create a new paint with the specified flags.
Paint(Paint paint) Create a new paint, initialized with the attributes in the specified paint parameter.
Public methods
floatascent() Return the distance above (negative) the baseline (ascent) based on the current typeface and text size.
intbreakText(char[] text, int index, int count, float maxWidth, float[] measuredWidth) Measure the text, stopping early if the measured width exceeds maxWidth.
intbreakText(String text, boolean measureForwards, float maxWidth,float[] measuredWidth) Measure the text, stopping early if the measured width exceeds maxWidth.
intbreakText(CharSequence text, int start, int end, boolean measureForwards, float maxWidth, float[] measuredWidth) Measure the text, stopping early if the measured width exceeds maxWidth.
voidclearShadowLayer() Clear the shadow layer.
floatdescent() Return the distance below (positive) the baseline (descent) based on the current typeface and text size.
booleanequalsForTextMeasurement(Paint other)Returns true of the passed Paint will have the same effect on text measurement
intgetAlpha()Helper to getColor() that just returns the color’s alpha value.
intgetColor()Return the paint’s color.
ColorFiltergetColorFilter()Get the paint’s colorfilter (maybe be null).
booleangetFillPath(Path src, Path dst)Applies any/all effects (patheffect, stroking) to src, returning the result in dst.
intgetFlags()Return the paint’s flags.
StringgetFontFeatureSettings()Returns the font feature settings.
floatgetFontMetrics(Paint.FontMetrics metrics)Return the font’s recommended interline spacing, given the Paint’s settings for typeface, textSize, etc.
Paint.FontMetricsgetFontMetrics()Allocates a new FontMetrics object, and then calls getFontMetrics(fm) with it, returning the object.
intgetFontMetricsInt(Paint.FontMetricsInt fmi)Return the font’s interline spacing, given the Paint’s settings for typeface, textSize, etc.
Paint.FontMetricsIntgetFontMetricsInt()
floatgetFontSpacing()Return the recommend line spacing based on the current typeface and text size.
StringgetFontVariationSettings()Returns the font variation settings.
intgetHinting()Return the paint’s hinting mode.
floatgetLetterSpacing()Return the paint’s letter-spacing for text.
MaskFiltergetMaskFilter()Get the paint’s maskfilter object.
intgetOffsetForAdvance(char[] text, int start, int end, int contextStart,int contextEnd, boolean isRtl, float advance)Get the character offset within the string whose position is closest to the specified horizontal position.
intgetOffsetForAdvance(CharSequence text, int start, int end, int contextStart, int contextEnd, boolean isRtl, float advance)
PathEffectgetPathEffect()Get the paint’s patheffect object.
floatgetRunAdvance(char[] text, int start, int end, int contextStart, int contextEnd, boolean isRtl, int offset)Measure cursor position within a run of text.
floatgetRunAdvance(CharSequence text, int start, int end, int contextStart,int contextEnd, boolean isRtl, int offset)
ShadergetShader()Get the paint’s shader object.
Paint.CapgetStrokeCap()Return the paint’s Cap, controlling how the start and end of stroked lines and paths are treated.
Paint.JoingetStrokeJoin()Return the paint’s stroke join type.
floatgetStrokeMiter()Return the paint’s stroke miter value.
floatgetStrokeWidth()Return the width for stroking.
Paint.StylegetStyle()Return the paint’s style, used for controlling how primitives’ geometries are interpreted (except for drawBitmap, which always assumes FILL_STYLE).
Paint.AligngetTextAlign()Return the paint’s Align value for drawing text.
voidgetTextBounds(String text, int start, int end, Rect bounds)Return in bounds (allocated by the caller) the smallest rectangle that encloses all of the characters, with an implied origin at (0,0).
voidgetTextBounds(char[] text, int index, int count, Rect bounds)Return in bounds (allocated by the caller) the smallest rectangle that encloses all of the characters, with an implied origin at (0,0).
LocalegetTextLocale()Get the text’s primary Locale.
LocaleListgetTextLocales()Get the text locale list.
voidgetTextPath(char[] text, int index, int count, float x, float y, Pathpath)Return the path (outline) for the specified text.
voidgetTextPath(String text, int start, int end, float x, float y, Pathpath)Return the path (outline) for the specified text.
floatgetTextScaleX()Return the paint’s horizontal scale factor for text.
floatgetTextSize()Return the paint’s text size.
floatgetTextSkewX()Return the paint’s horizontal skew factor for text.
intgetTextWidths(char[] text, int index, int count, float[] widths)Return the advance widths for the characters in the string.
intgetTextWidths(String text, float[] widths)Return the advance widths for the characters in the string.
intgetTextWidths(String text, int start, int end, float[] widths)Return the advance widths for the characters in the string.
intgetTextWidths(CharSequence text, int start, int end, float[] widths)Return the advance widths for the characters in the string.
TypefacegetTypeface()Get the paint’s typeface object.
XfermodegetXfermode()Get the paint’s transfer mode object.
booleanhasGlyph(String string)Determine whether the typeface set on the paint has a glyph supporting the string.
final booleanisAntiAlias()Helper for getFlags(), returning true if ANTI_ALIAS_FLAG bit is set AntiAliasing smooths out the edges of what is being drawn, but is has no impact on the interior of the shape.
final booleanisDither()Helper for getFlags(), returning true if DITHER_FLAG bit is set Dithering affects how colors that are higher precision than the device are down-sampled.
booleanisElegantTextHeight()Get the elegant metrics flag.
final booleanisFakeBoldText()Helper for getFlags(), returning true if FAKE_BOLD_TEXT_FLAG bit is set
final booleanisFilterBitmap()Whether or not the bitmap filter is activated.
final booleanisLinearText()Helper for getFlags(), returning true if LINEAR_TEXT_FLAG bit is set
final booleanisStrikeThruText()Helper for getFlags(), returning true if STRIKE_THRU_TEXT_FLAG bit is set
final booleanisSubpixelText()Helper for getFlags(), returning true if SUBPIXEL_TEXT_FLAG bit is set
final booleanisUnderlineText()Helper for getFlags(), returning true if UNDERLINE_TEXT_FLAG bit is set
floatmeasureText(char[] text, int index, int count)Return the width of the text.
floatmeasureText(CharSequence text, int start, int end)Return the width of the text.
floatmeasureText(String text, int start, int end)Return the width of the text.
floatmeasureText(String text)Return the width of the text.
voidreset()Restores the paint to its default settings.
voidset(Paint src)Copy the fields from src into this paint.
voidsetARGB(int a, int r, int g, int b)Helper to setColor(), that takes a,r,g,b and constructs the color int
voidsetAlpha(int a)Helper to setColor(), that only assigns the color’s alpha value, leaving its r,g,b values unchanged.
voidsetAntiAlias(boolean aa)Helper for setFlags(), setting or clearing the ANTI_ALIAS_FLAG bit AntiAliasing smooths out the edges of what is being drawn, but is has no impact on the interior of the shape.
voidsetColor(int color)Set the paint’s color.
ColorFiltersetColorFilter(ColorFilter filter)Set or clear the paint’s colorfilter, returning the parameter.
voidsetDither(boolean dither)Helper for setFlags(), setting or clearing the DITHER_FLAG bit Dithering affects how colors that are higher precision than the device are down-sampled.
voidsetElegantTextHeight(boolean elegant)Set the paint’s elegant height metrics flag.
voidsetFakeBoldText(boolean fakeBoldText)Helper for setFlags(), setting or clearing the FAKE_BOLD_TEXT_FLAG bit
voidsetFilterBitmap(boolean filter)Helper for setFlags(), setting or clearing the FILTER_BITMAP_FLAG bit.
voidsetFlags(int flags)Set the paint’s flags.
voidsetFontFeatureSettings(String settings)Set font feature settings.
booleansetFontVariationSettings(String fontVariationSettings)Sets TrueType or OpenType font variation settings.
voidsetHinting(int mode)Set the paint’s hinting mode.
voidsetLetterSpacing(float letterSpacing)Set the paint’s letter-spacing for text.
voidsetLinearText(boolean linearText)Helper for setFlags(), setting or clearing the LINEAR_TEXT_FLAG bit
MaskFiltersetMaskFilter(MaskFilter maskfilter)Set or clear the maskfilter object.
PathEffectsetPathEffect(PathEffect effect)Set or clear the patheffect object.
ShadersetShader(Shader shader)Set or clear the shader object.
voidsetShadowLayer(float radius, float dx, float dy, int shadowColor)This draws a shadow layer below the main layer, with the specified offset and color, and blur radius.
voidsetStrikeThruText(boolean strikeThruText)Helper for setFlags(), setting or clearing the STRIKE_THRU_TEXT_FLAG bit
voidsetStrokeCap(Paint.Cap cap)Set the paint’s Cap.
voidsetStrokeJoin(Paint.Join join)Set the paint’s Join.
voidsetStrokeMiter(float miter)Set the paint’s stroke miter value.
voidsetStrokeWidth(float width)Set the width for stroking.
voidsetStyle(Paint.Style style)Set the paint’s style, used for controlling how primitives’ geometries are interpreted (except for drawBitmap, which always assumes Fill).
voidsetSubpixelText(boolean subpixelText)Helper for setFlags(), setting or clearing the SUBPIXEL_TEXT_FLAG bit
voidsetTextAlign(Paint.Align align)Set the paint’s text alignment.
voidsetTextLocale(Locale locale)Set the text locale list to a one-member list consisting of just the locale.
voidsetTextLocales(LocaleList locales)Set the text locale list.
voidsetTextScaleX(float scaleX)Set the paint’s horizontal scale factor for text.
voidsetTextSize(float textSize)Set the paint’s text size.
voidsetTextSkewX(float skewX)Set the paint’s horizontal skew factor for text.
TypefacesetTypeface(Typeface typeface)Set or clear the typeface object.
voidsetUnderlineText(boolean underlineText)Helper for setFlags(), setting or clearing the UNDERLINE_TEXT_FLAG bit
XfermodesetXfermode(Xfermode xfermode)Set or clear the transfer mode object.

轉載于:https://www.cnblogs.com/cj5785/p/10664584.html

總結

以上是生活随笔為你收集整理的高级UI-画笔Paint的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。