当前位置: 七九推 > 移动技术>移动开发>Android > Android实现TV端大图浏览效果的全过程

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

2023年01月07日 Android 我要评论
前言最近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>

7.实现的效果如下:

总结

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

(0)
打赏 微信扫一扫 微信扫一扫

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2023  七九推 保留所有权利. 粤ICP备17035492号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com