package com.example.starterproject;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.Shader;
import android.util.AttributeSet;
import android.view.View;
import androidx.annotation.Nullable;
public class ArcView extends View {
private int mWidth;
private int mHeight;
private int mArcHeight; //圓弧的高度
private int mBgColor; //背景顏色
private int lgColor; //變化的最終顏色
private Paint mPaint; //畫筆
private LinearGradient linearGradient;
private Rect rect=new Rect(0,0,0,0);//普通的矩形
private Path path=new Path();//用來繪制曲面
public ArcView(Context context) {
this(context, null);
}
public ArcView(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public ArcView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.ArcView);
mArcHeight = typedArray.getDimensionPixelSize(R.styleable.ArcView_arcHeight, 0);
mBgColor=typedArray.getColor(R.styleable.ArcView_bgColor, Color.parseColor("#FFFFFF"));
lgColor = typedArray.getColor(R.styleable.ArcView_lgColor, mBgColor);
mPaint = new Paint();
mPaint.setAntiAlias(true);
typedArray.recycle();
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
// Log.d("----","onSizeChanged");
linearGradient = new LinearGradient(0,0,getMeasuredWidth(),0,
mBgColor,lgColor, Shader.TileMode.CLAMP
);
mPaint.setShader(linearGradient);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//設定成填充
mPaint.setStyle(Paint.Style.FILL);
mPaint.setColor(mBgColor);
//繪制矩形
rect.set(0, 0, mWidth, mHeight - mArcHeight);
canvas.drawRect(rect, mPaint);
//繪制路徑
path.moveTo(0, mHeight - mArcHeight);
path.quadTo(mWidth >> 1, mHeight, mWidth, mHeight - mArcHeight);
canvas.drawPath(path, mPaint);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
if (widthMode == MeasureSpec.EXACTLY) {
mWidth = widthSize;
}
if (heightMode == MeasureSpec.EXACTLY) {
mHeight = heightSize;
}
setMeasuredDimension(mWidth, mHeight);
}
}
以上代碼實作了自定義view,但是在以下layout中無法添加按鈕
<com.example.starterproject.ArcView
android:layout_width="match_parent"
android:layout_height="195dp"
app:arcHeight="23dp"
app:lgColor="@color/white"
app:bgColor="@color/white">
</com.example.starterproject.ArcView>
請問怎么能在該自定義view中添加按鈕、圖片?
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/254172.html
標籤:Android
上一篇:想收集APP開發者對于ios,andriod使用體驗,在哪里可以發調查問卷
下一篇:菜鳥咨詢
