自定义ImageView

图片等比例缩放,从0.0左边开始剪切 保证图片不变形
/**
 * @Description
 * @Created by YCH on 2015/11/9.
 */
public class CropImageView extends ImageView {


    /**
     * 画布的宽度
     */
    private int width;

    /**
     * 画布的高度
     */
    private int height;


    float scaleWidth = 1.0f;
    float scaleHeight = 1.0f;

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

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

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

        Drawable drawable = getDrawable();

        if (drawable != null) {
            Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
            if(bitmap != null){
                int bmWidth = bitmap.getWidth();
                int bmHeight = bitmap.getHeight();
                float scale = 1.0f;

                float scaleBitmap = (float)bmWidth/(float)bmHeight;//图片宽高比

                float scaleContainer = (float)width/(float)height;//容器宽高比

                //如果容器的比例大于图片的比例
                if(scaleContainer > scaleBitmap){
                    //根据宽度进行计算
                    scale = (float) width / (float) bmWidth;
                }else {
                    //根据高度进行计算
                    scale = (float) height / (float) bmHeight;
                }

                Matrix matrix = new Matrix();
                matrix.postScale(scaleWidth * scale, scaleHeight * scale);

                Rect rect = new Rect();
                rect.left = 0;
                rect.top = 0;
                rect.right = width;
                rect.bottom = height;
                Bitmap bm = Bitmap.createBitmap(bitmap, 0, 0, bmWidth, bmHeight, matrix, true);
                canvas.drawBitmap(bm, rect, rect, null);
            }
        }
    }
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值