Android漸變色圓角矩形框
阿新 • • 發佈:2019-01-01
效果如圖:
實現程式碼如下圖所示:
使用的方法如下:package com.example.demo.practice.ui; import android.content.Context; import android.graphics.Canvas; import android.graphics.LinearGradient; import android.graphics.Paint; import android.graphics.RectF; import android.graphics.Shader; import android.util.AttributeSet; import android.view.View; /** * Created by hanbo on 2018-01-11. */ public class GradientRoundSquare extends View{ private Paint paint; public GradientRoundSquare(Context context) { super(context); paint=new Paint(); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { setMeasuredDimension(widthMeasureSpec, heightMeasureSpec); super.onMeasure(widthMeasureSpec, heightMeasureSpec); } public GradientRoundSquare(Context context, AttributeSet attrs) { super(context, attrs); paint=new Paint(); } @Override protected void onDraw(Canvas canvas) { float width = getWidth(); float height = getHeight(); paint.setColor( StringToColor("#4ef1ff")); paint.setStrokeWidth(4); paint.setAntiAlias(true); paint.setStyle(Paint.Style.STROKE); RectF rectF = new RectF(0, 0, width, height); canvas.drawRoundRect(rectF,10,10,paint); super.onDraw(canvas); } /** * #顏色轉16進位制顏色 * * @param str {String} 顏色 * @return */ private int StringToColor(String str) { return 0xff000000 | Integer.parseInt(str.substring(2), 16); } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); if (changed) { paint.setShader(new LinearGradient( 0, 0, getWidth(), 0, StringToColor("#4ef1ff"), StringToColor("#0e9aeb"), Shader.TileMode.CLAMP)); } } }
<com.example.demo.practice.ui.GradientRoundSquare
android:layout_width="80dp"
android:layout_height="60dp"
android:layout_gravity="center_horizontal"/>