Android使用BitmapRegionDecoder获取指定区域的图片

        Android系统处理图片方面并不怎么理想,稍不注意就内存溢出。在处理大尺寸图片,有时候只需要显示指定区域的图片,Android在2.3中提供了BitmapRegionDecoder类来解决此问题。

        关于解决Bitmap加载内存溢出问题,可以查看Android使用BitmapFactory.Options解决加载大图片内存溢出问题

public class DisplayImageRegionActivity extends Activity implements OnTouchListener {
    private final Rect mRect = new Rect();
    private BitmapRegionDecoder mDecoder;
    private ImageView mView;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        mView = new ImageView(this);
        mView.setAdjustViewBounds(true);
        mView.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
        mView.setScaleType(ScaleType.CENTER);
        mView.setOnTouchListener(this);
        setContentView(mView);
        
        try {
            InputStream is = getResources().openRawResource(R.drawable.a);
            mDecoder = BitmapRegionDecoder.newInstance(is, true);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        final int action = event.getAction() & MotionEvent.ACTION_MASK;
        final int x = (int) event.getX();
        final int y = (int) event.getY();
        switch (action) {
        case MotionEvent.ACTION_DOWN:
        case MotionEvent.ACTION_MOVE:
            setImageRegion(x, y);
            break;
        }
        return true;
    }
    
    private void setImageRegion(int left, int top) {
//        BitmapFactory.Options opts = new BitmapFactory.Options();
        final int width = mView.getWidth();
        final int height = mView.getHeight();
        
        final int imgWidth = mDecoder.getWidth();
        final int imgHeight = mDecoder.getHeight();
        
        int right = left + width;
        int bottom = top + height;
        if(right > imgWidth) right = imgWidth;
        if(bottom > imgHeight) bottom = imgHeight;
        if(left < 0) left = 0;
        if(top < 0) top = 0;
        
        mRect.set(left, top, right, bottom);
        Bitmap bm = mDecoder.decodeRegion(mRect, null);
        mView.setImageBitmap(bm);
    }
}

转自: http://orgcent.com/android-bitmapregiondecoder-image/

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值