等比缩放图片为正方形

private class CircularDrawable extends Drawable {
    private final BitmapShader mBitmapShader;
    private final Paint mPaint;
    private Rect mRect;
    private int mLength;

    public CircularDrawable(Bitmap bitmap) {
        int w = bitmap.getWidth();
        int h = bitmap.getHeight();
        int targetSize = getResources().getDimensionPixelSize(R.dimen.capture_size);//缩放的宽高
        if (Math.min(w, h) < targetSize) {
            Matrix matrix = new Matrix();
            float scale = 1.0f;
            if (w > h) {
                scale = (float) targetSize / (float) h;
            } else {
                scale = (float) targetSize / (float) w;
            }
            matrix.postScale(scale, scale);
            bitmap = Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, true);
            w = (int) (w * scale);
            h = (int) (h * scale);
        }
        if (w > h) {
            mLength = h;
            bitmap = Bitmap.createBitmap(bitmap, (w - h) / 2, 0, h, h);
        } else if (w < h) {
            mLength = w;
            bitmap = Bitmap.createBitmap(bitmap, 0, (h - w) / 2, w, w);
        } else {
            mLength = w;
        }

        mBitmapShader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaint.setShader(mBitmapShader);
    }

    @Override
    protected void onBoundsChange(Rect bounds) {
        super.onBoundsChange(bounds);
        mRect = bounds;
    }

    @Override
    public void draw(Canvas canvas) {
        //begin add by punan for custom ui at 2016.06.14
        //canvas.drawRoundRect(new RectF(mRect), (mRect.right - mRect.left) / 2,
                //(mRect.bottom - mRect.top) / 2, mPaint);
        canvas.drawRoundRect(new RectF(mRect), 10, 10, mPaint);
    }

    @Override
    public int getOpacity() {
        return PixelFormat.TRANSLUCENT;
    }

    @Override
    public void setAlpha(int alpha) {
        mPaint.setAlpha(alpha);
    }

    @Override
    public void setColorFilter(ColorFilter filter) {
        mPaint.setColorFilter(filter);
    }

    @Override
    public int getIntrinsicWidth() {
        return mLength;
    }

    @Override
    public int getIntrinsicHeight() {
        return mLength;
    }

}

mimage.setImageDrawable(new CircularDrawable(bitmap));

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值