Android 仿徽章圆形view

package ja.burhanrashid52.photoeditor.view;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.widget.TextView;

/**
 * @author dell
 * @date 2019/2/21
 * @time 16:33
 **/
@SuppressLint("AppCompatCustomView")
public class CustomCirclePathView extends TextView {

    private Bitmap bitmap;
    private Paint paint;

    public CustomCirclePathView(Context context) {
        super(context);
        initPaint();
    }

    public CustomCirclePathView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initPaint();
    }

    public CustomCirclePathView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initPaint();
    }


    private void initPaint() {
        paint = new Paint();
        paint.setAntiAlias(true);
        paint.setPathEffect(new DashPathEffect(new float[]{20, 10}, 1));
    }

    public void setCircleBitmap(Bitmap bitmap) {
        this.bitmap = bitmap;
        invalidate();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        RectF bgOval = new RectF(0, 0, getWidth(), getHeight());
        if (bitmap != null) {
            Rect rectSrc = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
            canvas.drawBitmap(bitmap, rectSrc, bgOval, null);
            canvas.save();
        }

        RectF oval = new RectF(getTextSize(), getTextSize(), getWidth() - getTextSize(), getHeight() - getTextSize());
        Path path = new Path();
        path.addArc(oval, 95, 350);

        paint.setTextAlign(Paint.Align.CENTER);
        paint.setTextSize(getTextSize());
        paint.setTypeface(getTypeface());
        paint.setColor(getCurrentTextColor());
        paint.setStyle(Paint.Style.FILL);
        canvas.drawTextOnPath(getText().toString(), path, 0, 0, paint);
    }
}

android:hardwareAccelerated="false"时,会出现文字变形情况,当然也可以把bitmap改为红色圆环。

你可能感兴趣的:(Android 仿徽章圆形view)