文章详情

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

请输入下面的图形验证码

提交验证

短信预约提醒成功

Android实现文字动态高亮读取进度效果

2024-04-02 19:55

关注

本文实例为大家分享了Android实现文字动态高亮读取进度的具体代码,供大家参考,具体内容如下

1、效果图

类似歌词的效果。播放下面文字的音频,同时音频播放的进度和文字高亮进度保持一致。

2、代码结构和实现

简单的类图:

ISubtitleView接口代码如下:



public interface ISubtitleView {

    
    List<SubtitleItem> getSubtitleItemList();

    
    void setSubtitleItemList(List<SubtitleItem> linesTextList);

    
    void setDuration(long duration);

    
    void updatePts(long pts);

    
    void reset();
}
EMSubtitleView类的代码如下:


public class EMSubtitleView extends android.support.v7.widget.AppCompatTextView  implements ISubtitleView{

    private int mMeasuredWidth;
    private int mMeasuredHeight;
    private List<SubtitleItem> mSubtitleItemList;
    private List<LineEntity> mLinesTextList;
    private Paint mNormalPaint;
    private Paint mHLPaint;
    private long mPts = 0;
    private int mCurHLLine;
    private float mReadSubtitleCount;
    private Rect mLastHLRect;
    private int mHLTextColor;
    private long mDuration;
    private boolean mIsPlain = false;

    public EMSubtitleView(Context context) {
        this(context , null);
    }

    public EMSubtitleView(Context context, AttributeSet attrs) {
        this(context, attrs , 0);
    }

    public EMSubtitleView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mSubtitleItemList = new ArrayList<>();
        mLinesTextList = null;
        mLastHLRect = new Rect();
        mNormalPaint = null;
        initAttrs(attrs , defStyleAttr);

    }
    private void initAttrs(AttributeSet attrs , int defStyleAttr) {
        TypedArray ta = getContext().obtainStyledAttributes(attrs , R.styleable.EMSubtitleView , defStyleAttr , R.style.EMSubtitleViewDefaultTheme);
        for(int i = 0 ; i < ta.getIndexCount() ; i++){
            int index = ta.getIndex(i);
            if (index == R.styleable.EMSubtitleView_highLightTextColor) {
                mHLTextColor = ta.getColor(index, getResources().getColor(R.color.emvideovisit_color_FF9000));
            }
        }
        ta.recycle();
    }
    private void initHLPaint() {
        mHLPaint = new Paint(mNormalPaint);
        mHLPaint.setColor(mHLTextColor);
        mHLPaint.setTextSize(getTextSize());
    }

    
    public void setRichText(String text){
        mIsPlain = false;
        reset();
        setText(text);
        setDuration(mDuration , true);
    }

    
    public void setPlainText(String text){
        mIsPlain = true;
        reset();
        setText(text);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        if (mMeasuredWidth == 0 || mMeasuredHeight == 0) {
            mMeasuredWidth = getMeasuredWidth();
            mMeasuredHeight = getMeasuredHeight();
        }

        if(mIsPlain){
            super.onDraw(canvas);
            return;
        }
        if(mNormalPaint == null){
            super.onDraw(canvas);
            mNormalPaint = getPaint();
            initHLPaint();
            return;
        }

        if(mLinesTextList == null){
            fillLinesEntityListJustOnce();
        }
        //没有pts,绘制
        if(mPts <= 0){
            drawNormalText(canvas);
            return;
        }
        drawNormalText(canvas);
        calculateReadLineAndWordsCount();

        //绘制高亮部分歌词
        drawHLText(canvas);
    }

    private void drawHLText(Canvas canvas) {
        if(mCurHLLine >= 0){
            int curLineTextCount = 0;
            for(int i = 0 ; i < mLinesTextList.size() ; ++i){
                LineEntity entity = mLinesTextList.get(i);
                if(mCurHLLine > i){
                    canvas.drawText( entity.lineText , entity.left , entity.baseLine , mHLPaint);
                }else if(mCurHLLine == i && mReadSubtitleCount > 0 ){
                    canvas.save();
                    mLastHLRect.set(entity.left , entity.top , entity.left + (int) (mHLPaint.measureText(entity.lineText)*1.0f/entity.lineText.length()*(mReadSubtitleCount-curLineTextCount)), entity.bottom);
                    canvas.clipRect(mLastHLRect );
                    canvas.drawText( entity.lineText , entity.left , entity.baseLine , mHLPaint);
                    canvas.restore();
                    //遮挡的话需要滚动
                    if(entity.baseLine > getHeight()){
                        if(getScrollY() != entity.bottom - getHeight() + 1){
                            setScrollY( entity.bottom - getHeight() + 1);
                        }
                    }
                    break;
                }
                curLineTextCount += entity.lineText.length();
            }
        }
    }

    private void calculateReadLineAndWordsCount() {
        float curSubtitleCount = 0;
        for(SubtitleItem subtitleItem :  mSubtitleItemList){
            //文字之间不可以有空隙,否则mCurHLLine可能一直为-1;
            if(mPts >= subtitleItem.getStartTime() && mPts < subtitleItem.getEndTime()){
                float lineOffset = (subtitleItem.getWords().length()*1.0f/(subtitleItem.getEndTime() - subtitleItem.getStartTime()))*(mPts-subtitleItem.getStartTime());
                curSubtitleCount += lineOffset;
                int curLineTextCount = 0;
                for(int i = 0 ; i < mLinesTextList.size() ; ++i){
                    curLineTextCount += mLinesTextList.get(i).lineText.length();
                    if(curLineTextCount > curSubtitleCount){
                        mCurHLLine = i;
                        break;
                    }
                }
                break;
            }
            curSubtitleCount += subtitleItem.getWords().length();
        }
        mReadSubtitleCount = curSubtitleCount;
    }

    private void fillLinesEntityListJustOnce() {
        if(mLinesTextList != null){
            return;
        }
        mLinesTextList = new ArrayList<>();
        Layout layout = getLayout();
        int line=getLayout().getLineCount();
        String text=layout.getText().toString();
        for(int i=0;i<line;i++){
            int start=layout.getLineStart(i);
            int end=layout.getLineEnd(i);
            int left = (int) layout.getLineLeft(i);
            int baseLine = layout.getLineBaseline(i);
            Paint.FontMetrics fontMetrics = getPaint().getFontMetrics();
            int top = (int) (baseLine + fontMetrics.top);
            int bottom = (int) (baseLine + fontMetrics.bottom);
            int ascent = (int) (baseLine + fontMetrics.ascent);
            int descent = (int) (baseLine + fontMetrics.descent);

            mLinesTextList.add(new LineEntity(text.substring(start, end) , top , bottom , ascent , descent ,baseLine , left));
        }
    }

    private void drawNormalText(Canvas canvas) {
        for(LineEntity entity : mLinesTextList){
            canvas.drawText(entity.lineText, entity.left,  entity.baseLine , mNormalPaint);
        }
    }

    public List<SubtitleItem> getSubtitleItemList() {
        return mSubtitleItemList;
    }

    
    public void setSubtitleItemList(List<SubtitleItem> linesTextList) {
        if(mSubtitleItemList != null){
            mSubtitleItemList.clear();
            mSubtitleItemList.addAll(linesTextList);
        }else{
            this.mSubtitleItemList = linesTextList;
        }
    }

    
    public void setDuration(long duration){
        setDuration( duration , false);
    }

    private void setDuration(long duration , boolean force){
        if((duration > 0 && mDuration != duration) || force){
            mDuration = duration;
            if(mSubtitleItemList != null){
                mSubtitleItemList.clear();
            }else{
                this.mSubtitleItemList = new ArrayList<>();
            }
            mSubtitleItemList.add(new SubtitleItem(getText().toString() , 0 , duration));
        }
    }

    
    public void updatePts(long pts){
        mPts = pts;
        postInvalidate();
    }

    
    public void reset(){
        mPts = 0;
        mCurHLLine = 0;
        mReadSubtitleCount = 0;
        mLinesTextList = null;
        mNormalPaint = null;
        setScrollY(0);
        postInvalidate();

    }

    static class LineEntity{
       String lineText;
       int top;
       int bottom;
       int ascent;
       int descent;
       int baseLine;
       int left;


        public LineEntity(String lineText, int top, int bottom, int ascent, int descent, int baseLine, int left) {
            this.lineText = lineText;
            this.top = top;
            this.bottom = bottom;
            this.ascent = ascent;
            this.descent = descent;
            this.baseLine = baseLine;
            this.left = left;
        }

    }
}

布局文件里使用类似如下:


<com.eastmoney.emvideovisit.view.EMSubtitleView
        android:id="@+id/play_text"
        android:layout_width="match_parent"
        android:layout_height="@dimen/emvideovisit_dp_60"
        android:layout_marginLeft="@dimen/emvideovisit_dp_60"
        android:layout_marginRight="@dimen/emvideovisit_dp_60"
        android:gravity="center_horizontal"
        android:layout_marginTop="@dimen/emvideovisit_dp_20"
        android:textColor="#fff"
        app:highLightTextColor="#A6EA5504"
        android:text="@string/emvideovisit_string_headset_tips"
        android:textSize="@dimen/emvideovisit_dp_16"
        android:layout_marginBottom="@dimen/emvideovisit_dp_4"/>

3、其它

处理过程中文字位置的参数需要注意:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程网。

阅读原文内容投诉

免责声明:

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

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

软考中级精品资料免费领

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

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

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

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

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

    难度     224人已做
    查看

相关文章

发现更多好内容

猜你喜欢

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