您的位置:首页 > 移动开发 > Android开发

Android2.3使用BitmapRegionDecoder获取指定区域的图片

2014-06-27 11:12 309 查看
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);

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: