美文网首页高级UI
android 顶部自定义曲面背景

android 顶部自定义曲面背景

作者: 一个冬季 | 来源:发表于2020-03-04 22:35 被阅读0次
注意

1、该自定义不适合图片


自定义曲面背景.jpg

2、arcRectangleHeight 数字越大,越平滑 。 arcRectangleBgColor 修改颜色

使用方式
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <com.example.arcrectangleapplication.ArcRectangleView
        android:layout_width="match_parent"
        app:arcRectangleBgColor="@color/colorAccent"
        app:arcRectangleHeight="60"
        android:layout_height="158dp"/>

</FrameLayout>
public class ArcRectangleView extends View {
    private Context mContext;
    private Paint mPaint;
    private int paintWidth = 10;
    private int rectangleHeight = 60;//单位是DP
    public ArcRectangleView(Context context) {
        this(context,null);
    }

    public ArcRectangleView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs,0);
    }

    public ArcRectangleView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray typedArray =context.obtainStyledAttributes(attrs,R.styleable.ArcRectangleView);
        int rectBgColor = typedArray.getColor(R.styleable.ArcRectangleView_arcRectangleBgColor, Color.parseColor("#999999"));
        rectangleHeight = typedArray.getInteger(R.styleable.ArcRectangleView_arcRectangleHeight,60);
        this.mContext = context;
        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mPaint.setColor(rectBgColor);
        mPaint.setStrokeWidth(paintWidth);
        mPaint.setStyle(Paint.Style.FILL);
    }



    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        RectF rectF = new RectF(-dip2px(mContext,rectangleHeight),0,getMeasuredWidth() + dip2px(mContext,rectangleHeight),getMeasuredHeight());
        Path path = new Path();
        path.moveTo(getMeasuredWidth() / 2,0);
        path.arcTo(rectF,0,180);
        path.close();
        canvas.drawPath(path,mPaint);
        RectF rectF1 = new RectF(0,0,getMeasuredWidth(),getMeasuredHeight() / 2);
        canvas.drawRect(rectF1,mPaint);
    }



    public int dip2px(Context context,float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }
}
<resources>
    <declare-styleable name="ArcRectangleView">
        <attr name="arcRectangleBgColor" format="color"/>
        <attr name="arcRectangleHeight" format="integer"/>
    </declare-styleable>
</resources>

相关文章

网友评论

    本文标题:android 顶部自定义曲面背景

    本文链接:https://www.haomeiwen.com/subject/fvuwlhtx.html