AndroidTV开发13——实现TV端大图浏览
最近TV开发需要加载的图片很长,大小也很大,并且还不允许压缩。比如显示:世界地图、清明上河图、微博长图、海报、活动照片等。
那么对于这种需求,该如何做呢?
首先不压缩,按照原图尺寸加载,那么屏幕肯定是不够大的,并且考虑到内存的情况,不可能一次性整图加载到内存中,所以肯定是局部加载,那么就需要用到一个类:
-
BitmapRegionDecoder
其次,既然屏幕显示不完,那么最起码要添加一个上下左右拖动的手势,让用户可以拖动查看。
实现方式有很多:
1.BitmapRegionDecoder:
分片加载,使用系统BitmapRegionDecoder去加载本地的图片,调用bitmapRegionDecoder.decodeRegion解析图片的矩形区域,返回bitmap,最终显示在ImageView上。这种方案需要手动处理滑动、缩放手势,网络图片还要处理缓存策略等问题。实现方式比较繁琐也不是很推荐。
2.SubsamplingScaleImageView
一款封装BitmapRegionDecoder的三方库,已经处理了滑动,缩放手势。我们可以考虑选择这个库来进行加载长图,但是官方上的Demo示例加载的长图均为本地图片。这可能并不符合我们的网络场景需求,所以对于网络图片,我们还要考虑不同的加载框架,
3.Glide+SubsamplingScaleImageView混合加载渲染
对于图片加载框架,Glide当然是首选,我们使用Glide进行网络图片的下载和缓存管理,FileTarget作为桥梁,SubsamplingScaleImageView进行本地资源图片的分片加载,看起来很靠谱,那么一起来实现吧。
4.自定义LongImageView,结合BitmapRegionDecoder使用
本文采取的第四种方式,代码如下:
public class LongImageView extends AppCompatImageView { private String TAG = getClass().getSimpleName(); private int mTargetY = 0; private int scrollDistance = 0; private int imgWidth = 0, imgHeight = 0; private Bitmap imgBitmap = null; private Bitmap holderBitmap; private BitmapRegionDecoder bitmapRegionDecoder; private boolean isScrolling = false; private float startY = -1; private int mStartTargetY = -1; private BitmapFactory.Options scaleOptions = new BitmapFactory.Options(); public Bitmap bitmap; public static final String EVENT_PROP_URL = "url"; public static final String EVENT_PROP_BITMAP_WIDTH = "resourceWidth"; public static final String EVENT_PROP_BITMAP_HEIGHT = "resourceHeight"; public LongImageView(Context context) { super(context); init(); } public LongImageView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); init(); } public LongImageView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } private void init() { //遥控器按键事件 setOnKeyListener(new OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { scrollDistance = scrollDistance <= 0 ? getHeight() : scrollDistance; if (event.getAction() == KeyEvent.ACTION_DOWN && !isScrolling) { switch (event.getKeyCode()) { case KeyEvent.KEYCODE_DPAD_UP: scrollBy(0 - viewHeight2ImageHeight(scrollDistance)); break; case KeyEvent.KEYCODE_DPAD_DOWN: scrollBy(viewHeight2ImageHeight(scrollDistance)); break; } } return false; } }); //响应鼠标拖拽(手指也可以) setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: Log.e(TAG, " touch down"); startY = event.getRawY(); mStartTargetY = mTargetY; break; case MotionEvent.ACTION_MOVE: float currentY = event.getRawY(); mTargetY = mStartTargetY + (int) (viewHeight2ImageHeight((int) (startY - currentY)) * 1f); mTargetY = Math.max(0, Math.min(mTargetY, imgHeight - viewHeight2ImageHeight(getHeight()))); Log.e(TAG, " touch move " + mTargetY); invalidate(); break; case MotionEvent.ACTION_UP: Log.e(TAG, " touch up"); startY = -1; break; } return true; } }); } private void startScroll(int targetY) { targetY = Math.max(0, Math.min(targetY, imgHeight - viewHeight2ImageHeight(getHeight()))); ValueAnimator valueAnimator = ValueAnimator.ofInt(mTargetY, targetY); valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { mTargetY = (int) animation.getAnimatedValue(); invalidate(); } }); valueAnimator.addListener(new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animation) { isScrolling = true; } @Override public void onAnimationEnd(Animator animation) { isScrolling = false; } @Override public void onAnimationCancel(Animator animation) { isScrolling = false; } @Override public void onAnimationRepeat(Animator animation) { } }); valueAnimator.setInterpolator(new LinearInterpolator()); //设置滑动速度 valueAnimator.setDuration(10); valueAnimator.start(); } /** * 根据InputStream 生成 BitmapRegionDecoder * * @param imgStream */ public void setImageStream(InputStream imgStream) { try { BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeStream(imgStream, new Rect(0, 0, 0, 0), options); imgWidth = options.outWidth; imgHeight = options.outHeight; //寻找最佳的缩放比例 int viewHeight2ImageHeight = viewHeight2ImageHeight(getHeight()); //设置缩放比例 int scale = getScaleValue(imgWidth, viewHeight2ImageHeight, 1); scaleOptions.inSampleSize = scale; } catch (Exception e) { e.printStackTrace(); } try { bitmapRegionDecoder = BitmapRegionDecoder.newInstance(imgStream, false); } catch (Exception e) { e.printStackTrace(); } } /** * 根据图片文件 生成 BitmapRegionDecoder * * @param imgFile */ public void setImageFile(File imgFile) { try { BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(imgFile.getAbsolutePath(), options); imgWidth = options.outWidth; imgHeight = options.outHeight; //寻找最佳的缩放比例 int viewHeight2ImageHeight = viewHeight2ImageHeight(getHeight()); int scale = getScaleValue(imgWidth, viewHeight2ImageHeight, 1); scaleOptions.inSampleSize = scale; } catch (Exception e) { e.printStackTrace(); } try { bitmapRegionDecoder = BitmapRegionDecoder.newInstance(imgFile.getAbsolutePath(), false); } catch (Exception e) { e.printStackTrace(); } } private int getScaleValue(int imgWidth, int imgHeight, int scaleValue) { long memory = Runtime.getRuntime().maxMemory() / 4; if (memory > 0) { if (imgWidth * imgHeight * 4 > memory) { scaleValue += 1; return getScaleValue(imgWidth, imgHeight, scaleValue); } } return scaleValue; } /** * 根据图片Id 生成 BitmapRegionDecoder * * @param resourceId */ @SuppressLint("ResourceType") public void setImageResource(int resourceId) { InputStream imgStream = getResources().openRawResource(resourceId); setImageStream(imgStream); } /** * 设置占位图 * * @param holderId */ public void setPlaceHolder(int holderId) { holderBitmap = BitmapFactory.decodeResource(getResources(), holderId); } /** * 滑动到具体的位置 * * @param targetY */ private void scrollTo(int targetY) { startScroll(targetY); } /** * 设置相对于当前,继续滑动的距离。小于0 向上滑动,大于0向下滑动 * * @param distance */ private void scrollBy(int distance) { startScroll(mTargetY + distance); } /** * 设置每次滑动的距离 * * @param scrollDistance */ public void setScrollDistance(int scrollDistance) { this.scrollDistance = scrollDistance; } @Override protected void onDraw(Canvas canvas) { Log.e(getClass().getSimpleName(), "draw start " + getWidth() + " " + getHeight()); canvas.save(); int sr = canvas.saveLayer(0, 0, getWidth(), getHeight(), null, Canvas.ALL_SAVE_FLAG); Paint paint = new Paint(); paint.setAntiAlias(true); if (bitmapRegionDecoder != null) { int targetHeight = viewHeight2ImageHeight(getHeight());//根据控件的高度获取需要在原始图片上截取的高度 Log.e(getClass().getSimpleName(), "targetHeight " + targetHeight); Log.e(getClass().getSimpleName(), "draw resource " + " " + imgWidth + " " + imgHeight + " " + mTargetY + " " + targetHeight); imgBitmap = null; if (imgHeight - mTargetY >= targetHeight) {//剩余区域大于 当前控件高度 imgBitmap = bitmapRegionDecoder.decodeRegion(new Rect(0, mTargetY, imgWidth, mTargetY + targetHeight) , scaleOptions); } else {//剩余区域小于 当前控件高度 imgBitmap = bitmapRegionDecoder.decodeRegion(new Rect(0, imgHeight - targetHeight, imgWidth, imgHeight) , scaleOptions); } if (imgBitmap != null) { //绘制需要展示的图片 canvas.drawBitmap(imgBitmap , new Rect(0, 0, imgBitmap.getWidth(), imgBitmap.getHeight()) , new Rect(0, 0, getWidth(), getHeight()) , paint); } imgBitmap = null; holderBitmap = null; } else { if (holderBitmap != null) {//绘制占位图 canvas.drawBitmap(holderBitmap , new Rect(0, 0, holderBitmap.getWidth(), holderBitmap.getHeight()) , new Rect(0, 0, getWidth(), getHeight()) , paint); } } canvas.restoreToCount(sr); canvas.restore(); Log.e(getClass().getSimpleName(), "draw end"); } /** * 图片高度转为相对于控件的高度 * * @param imgHeight * @return */ private int imageHeight2ViewHeight(int imgHeight) { if (this.imgHeight <= 0) { return 0; } return (int) (imgHeight / ((float) getWidth() / imgWidth * imgHeight) * getHeight()); } /** * 控件高度转为相对于图片高度 * * @param viewHeight * @return */ private int viewHeight2ImageHeight(int viewHeight) { if (getHeight() <= 0) { return 0; } return (int) (viewHeight / ((float) getWidth() / imgWidth * imgHeight) * imgHeight); } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); //回收资源和释放内存 release(); } public void release() { if (imgBitmap != null && !imgBitmap.isRecycled()) { imgBitmap.recycle(); imgBitmap = null; } if (holderBitmap != null && !holderBitmap.isRecycled()) { holderBitmap.recycle(); holderBitmap = null; } System.gc(); } }
5.在MainActivity中的使用:
/** * @auth: njb * @date: 2022/11/7 0:11 * @desc: */ public class MainActivity extends AppCompatActivity { public String url = "https://qcloudimg-moss.cp47.ott.cibntv.net/data_center/files/2022/10/26/67a66d35-3f7c-4de8-9dfe-c706e42f44f2.jpg"; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); } private void initView() { LongImageView mImageView = findViewById(R.id.imageView); mImageView.setScrollDistance((int) ((float) ScreenUtils.getScreenHeight(this) / 3 * 2)); mImageView.setFocusable(true); try { Glide.with(this) .load(url) .downloadOnly(new SimpleTarget<File>() { @Override public void onResourceReady(@NonNull File resource, @Nullable Transition<? super File> transition) { mImageView.setImageFile(resource); } }); } catch (Exception e) { e.printStackTrace(); } } }
6.布局文件代码:
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" xmlns:app="http://schemas.android.com/apk/res-auto"> <com.example.longimageView.view.LongImageView android:id="@+id/imageView" android:layout_width="0dp" android:layout_height="0dp" android:focusable="true" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintBottom_toBottomOf="parent"/> </androidx.constraintlayout.widget.ConstraintLayout>