Android开发经验谈Android开发Android自定义控件

画一个简单的田字格

2020-03-07  本文已影响0人  nickieeee
image.png

上代码

package com.nick.customview;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.support.annotation.Nullable;
import android.support.v7.widget.AppCompatImageView;
import android.util.AttributeSet;


public class SimpleRectangle extends AppCompatImageView {

    public SimpleRectangle(Context context) {
        super(context);
    }

    public SimpleRectangle(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public SimpleRectangle(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public void draw(Canvas canvas) {
        Paint paint = new Paint();
        paint.setColor(Color.BLUE);
        paint.setStyle(Paint.Style.STROKE);
        paint.setAlpha(250);
        paint.setStrokeWidth(10.0f);
        paint.setStrokeCap(Paint.Cap.ROUND);
        RectF rectF = new RectF(80, 80, getWidth()- 80, getHeight()- 80);
        canvas.drawRoundRect(rectF, 30, 30, paint);
        canvas.drawLine(80, getHeight()/2, getWidth()- 80, getHeight()/2, paint);
        canvas.drawLine(getWidth()/2, 80, getWidth()/2, getHeight()- 80, paint);
        super.draw(canvas);
    }
}

一开始遇到的问题是怎么让边框的角变成圆角,后来查到添加paint的一个属性就可以做到。看developers怎么介绍这个牛逼的属性的:

paint.setStrokeCap(Paint.Cap.ROUND);

image.png

当画笔paint的样式是描边或这描边填充时使用Cap参数来设置线头的样式。

上一篇下一篇

猜你喜欢

热点阅读