剪切图片成圆形图片

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Shader;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.OvalShape;
import android.util.AttributeSet;
import android.widget.ImageView;


/**
 * 圆形背景ImageView
 */
public class CircleImageView extends ImageView {
    private BitmapShader bitmapShader = null;
    private Bitmap bitmap = null;
    private ShapeDrawable shapeDrawable = null;
    private int width = 0;
    private int height = 0;


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


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


    public CircleImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }


    @Override
    protected void onDraw(Canvas canvas) {
        width = getWidth();
        height = getHeight();


        bitmap = ((BitmapDrawable) getDrawable()).getBitmap();
        // 重新生成指定大小的图片
        bitmap = Bitmap.createScaledBitmap(bitmap, width, height,
                true);


        // 构造渲染器BitmapShader
        bitmapShader = new BitmapShader(bitmap, Shader.TileMode.MIRROR,
                Shader.TileMode.REPEAT);


        // 将图片裁剪为椭圆形
        // 构建ShapeDrawable对象并定义形状为椭圆
        shapeDrawable = new ShapeDrawable(new OvalShape());
        // 得到画笔并设置渲染器
        shapeDrawable.getPaint().setShader(bitmapShader);
        // 设置显示区域
        shapeDrawable.setBounds(0, 0, width, height);
        // 绘制shapeDrawable
        shapeDrawable.draw(canvas);
    }


}

转载于:https://my.oschina.net/u/698243/blog/88376

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值