Android可以动态控制图片显示区域的自定义ImageView

r囧r小猫 2022-08-18 13:27 292阅读 0赞

一个imageView经常需要动态的控制里面图片的显示区域,比如根据触摸去改变里面图片的显示位置,或者放大镜效果等,于是做了这么个自定义控件,亲测好用,而且已经做了参数容错,只要传入上下左右的偏移量即可,不用担心传入的数过大。而且还可以设置默认的偏移量

  1. package com.npi.blureffect;
  2. import android.content.Context;
  3. import android.graphics.Bitmap;
  4. import android.graphics.Canvas;
  5. import android.graphics.Paint;
  6. import android.util.AttributeSet;
  7. import android.util.Log;
  8. import android.view.View;
  9. /**
  10. * Custom view used to render an horizontal part (slice) of an image.
  11. *
  12. * @author Nicolas POMEPUY
  13. *
  14. */
  15. class ScrollableImageView extends View {
  16. // A bitmap adapted to the View size
  17. private Bitmap adaptedImage;
  18. // A Paint object used to render the image
  19. private Paint paint = new Paint();
  20. // The original Bitmap
  21. private Bitmap originalImage;
  22. // The screen width used to render the image
  23. private int scrollY = 0;//初始纵轴偏移,应该为正
  24. private int scrollX = 0;//初始横轴偏移,应该为正
  25. public ScrollableImageView(Context context, AttributeSet attrs, int defStyle) {
  26. super(context, attrs, defStyle);
  27. }
  28. public ScrollableImageView(Context context, AttributeSet attrs) {
  29. this(context, attrs, 0);
  30. }
  31. public ScrollableImageView(Context context) {
  32. this(context, null);
  33. }
  34. /**
  35. * Draws the view if the adapted image is not null
  36. */
  37. @Override
  38. protected void onDraw(Canvas canvas) {
  39. if (adaptedImage != null)
  40. canvas.drawBitmap(adaptedImage, 0, 0, paint);
  41. }
  42. /**
  43. * Handle an external scroll and render the image by switching it by a
  44. * distance
  45. * 最核心的方法
  46. * 传入的应为正值,为向下和向右的偏移量
  47. * @param distY
  48. * the distance from the top
  49. */
  50. public void handleScroll(float distY,float distX) {
  51. if (getHeight() > 0 && getWidth()>0 && originalImage != null) {
  52. Log.i("Alex", "scrolly是"+scrollY+" distY是"+distY+" origi高是"+originalImage.getHeight()+" 自高是"+getHeight());
  53. Log.i("Alex", "scrolly是"+scrollX+" distX是"+distX+" origi宽是"+originalImage.getWidth()+" 自宽是"+getWidth());
  54. //distY为正值,正值向下滑
  55. //scrollY一直是0或负值
  56. //getHeight是自高
  57. if (Math.abs(scrollY+distY) <= originalImage.getHeight() - getHeight() && Math.abs(scrollX+distX) <= originalImage.getWidth() - getWidth()) {
  58. adaptedImage = Bitmap.createBitmap(originalImage, (int)distX+scrollX, (int) distY+scrollY, getWidth(), getHeight());
  59. invalidate();
  60. }
  61. }
  62. }
  63. public void setoriginalImage(Bitmap bmp) {
  64. this.originalImage = bmp;
  65. adaptedImage = Bitmap.createBitmap(bmp);
  66. invalidate();
  67. }
  68. }

调用方法

1,先抓到对象

ScrollableImageView image = (ScrollableImageView) findViewById(R.id.window);

2、设置显示内容

image .setoriginalImage(一个bitmap对象);

3、确定移动距离

window.handleScroll(10f,20f);//横纵都移动,一般放在ontouchListener中执行

发表评论

表情:
评论列表 (有 0 条评论,292人围观)

还没有评论,来说两句吧...

相关阅读