android开发,绘制圆形图片并添加文字居中显示

来源:互联网 发布:linux grub命令进win 编辑:程序博客网 时间:2024/05/18 02:30
public class Yuan extends ImageView {    private Paint Paint;    private TextPaint textPaint;    private String str = null;    public Yuan(Context context) {        this(context, null);    }    public Yuan(Context context, AttributeSet attrs) {        this(context, attrs, 0);    }    public Yuan(Context context, AttributeSet attrs, int defStyleAttr) {        super(context, attrs, defStyleAttr);        init();    }    private void init() {        textPaint = new TextPaint();        textPaint.setColor(Color.WHITE);//文字颜色        textPaint.setAntiAlias(true);//抗锯齿        textPaint.setTextSize(20);//文字大小    }    @Override    protected void onDraw(Canvas canvas) {        //清空样式        Paint = new Paint();        Paint.setAntiAlias(true);        //Paint.setColor(getResources().getColor(R.color.yuan));        //Paint.setStyle(android.graphics.Paint.Style.STROKE);//这句关系到图片画出来的样式如果需要画原图则不需要这句话        //要圆形图片就不能要默认的我们把它注掉        // super.onDraw(canvas);        //获取我们的图片        Drawable drawable = getDrawable();        if (drawable == null) {            return;        }        //获取bitmap对象        Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();        if (bitmap == null) {            return;        }        //因为要绘制圆形图片为了防止我们的高宽不一致我们取一下高宽的最小值        int r = getWidth() > getHeight() ? getHeight() : getWidth();        //创建新的画布,需要一个新的图片,我們來創建下,图片大小的話我們取控件最小值        Bitmap creatbitmap = Bitmap.createBitmap(r, r, Bitmap.Config.ARGB_8888);        Canvas newcanvs = new Canvas(creatbitmap);        //我們現在绘制一个圆形        newcanvs.drawCircle(r / 2, r / 2, r / 2, Paint);        //我們取图片跟圆形相交部分        Paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));        //绘制图片        newcanvs.drawBitmap(bitmap, new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight()), new Rect(0, 0, r, r), Paint);        canvas.drawBitmap(creatbitmap, new Rect(0, 0, creatbitmap.getWidth(), creatbitmap.getHeight()), new Rect(0, 0, r, r), null);        //绘制数字        if (str != null) {            canvas.drawText(str, getWidth() / 2 - textPaint.measureText(str) / 2, getHeight() / 2 + 1.5f * textPaint.getFontMetrics().bottom, textPaint);        }else {        }    }    /**     * 公开方法,将要绘制的文字传入     * @param str     */    public void settextstr(String str) {        this.str = str;        invalidate();    }}
0 0
原创粉丝点击