android 图片上覆盖文字

来源:互联网 发布:苹果手机怎么更新淘宝 编辑:程序博客网 时间:2024/05/16 02:09

此例在圆形头像上覆盖文字,RoundedImageView为开源圆形图片空间


java:

/** * 图片上或者空间上覆盖文字(此为圆形图片上) * Created by yjc on 2017/3/21. */public class AddTextRoundImageView extends RoundedImageView {    private Paint mPaint;    private String str;    public AddTextRoundImageView(Context context) {        super(context);    }    public AddTextRoundImageView(Context context, AttributeSet attrs) {        super(context, attrs);    }    public AddTextRoundImageView(Context context, AttributeSet attrs, int defStyle) {        super(context, attrs, defStyle);    }    @Override    protected void onDraw(Canvas canvas) {        super.onDraw(canvas);        if (TextUtils.isEmpty(str)){            return;        }
        mPaint = new Paint();        mPaint.setColor(Color.WHITE);        mPaint.setTextSize((int) TypedValue.applyDimension(                TypedValue.COMPLEX_UNIT_SP, 20, getResources().getDisplayMetrics()));//        mPaint.setTextAlign(Paint.Align.CENTER);        //拿到字符串的宽度        float stringWidth = mPaint.measureText(str);        float x =(getWidth()-stringWidth)/2;        //文字的y轴坐标        Paint.FontMetrics fontMetrics = mPaint.getFontMetrics();        float y = getHeight() / 2 + (Math.abs(fontMetrics.ascent) - fontMetrics.descent) / 2;        canvas.drawText(str,x, y,mPaint);
} @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); } //添加文字方法 public void addText(String str){ this.str = str; }}


0 0
原创粉丝点击