文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

Android实现TV端大图浏览效果的全过程

2023-01-06 18:00

关注

前言

最近TV开发需要加载的图片很长,大小也很大,并且还不允许压缩。比如显示:世界地图、清明上河图、微博长图、海报、活动照片等。

那么对于这种需求,该如何做呢?

首先不压缩,按照原图尺寸加载,那么屏幕肯定是不够大的,并且考虑到内存的情况,不可能一次性整图加载到内存中,所以肯定是局部加载,那么就需要用到一个类:

其次,既然屏幕显示不完,那么最起码要添加一个上下左右拖动的手势,让用户可以拖动查看。

实现方式有很多:

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();
    }
​
​
    
    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();
        }
    }
​
    
    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;
    }
​
    
    @SuppressLint("ResourceType")
    public void setImageResource(int resourceId) {
        InputStream imgStream = getResources().openRawResource(resourceId);
        setImageStream(imgStream);
    }
​
    
    public void setPlaceHolder(int holderId) {
        holderBitmap = BitmapFactory.decodeResource(getResources(), holderId);
    }
​
    
    private void scrollTo(int targetY) {
        startScroll(targetY);
    }
​
    
    private void scrollBy(int distance) {
        startScroll(mTargetY + distance);
    }
​
    
    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");
    }
​
    
    private int imageHeight2ViewHeight(int imgHeight) {
        if (this.imgHeight <= 0) {
            return 0;
        }
        return (int) (imgHeight / ((float) getWidth() / imgWidth * imgHeight) * getHeight());
    }
​
    
    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中的使用:


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>

7.实现的效果如下:

总结

到此这篇关于Android实现TV端大图浏览效果的文章就介绍到这了,更多相关Android TV端大图浏览内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

阅读原文内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     807人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     351人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     314人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     433人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     221人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-移动开发
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯