自定义波形图View,LayoutInflater动态加载控件保存为本地图片

效果图:

页面布局:

css 复制代码
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="@dimen/dp_145"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:background="@color/white">

    <TextView
        android:id="@+id/tv_index"
        android:layout_width="@dimen/dp_30"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        android:background="@color/common_btn_clicked"
        android:gravity="center"
        android:textColor="@color/white"
        android:textSize="@dimen/sp_14"
        tools:text="TH"/>

    <RelativeLayout
        android:id="@+id/rl_wave_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/white">

        <com.kl.common_base.view.wave.GridView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:bgColor="#f0d3a9"/>

        <com.kl.common_base.view.wave.PdfEcgWaveView
            android:id="@+id/wave_view"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:visibility="visible" />

        <TextView
            android:id="@+id/tv_file_create_date"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="@dimen/dp_20"
            android:layout_marginTop="@dimen/dp_10"
            android:text=""
            android:textColor="@color/colorPrimary"
            android:textSize="@dimen/sp_12"
            tools:text="2019年6月26日11:54" />
    </RelativeLayout>
</LinearLayout>

自定义波形图控件:

css 复制代码
package com.kl.common_base.view.wave;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;

import com.kl.common_base.R;
import com.kl.common_base.utils.SizeUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class PdfEcgWaveView extends View {
    private List<Short> pointList = Collections.synchronizedList(new LinkedList<>());
    private Paint mPaint;
    private Paint mPaintLine;
    private int mWidth = 0;
    private int mHeight = 0;
    private int mCenterY = 0;
    public float points[];
    List<Short> nativeDatas = null;
    private int len = 0;
    private int index = 0;

    private int zoom;
    private float gapX = 0.2f;
    private int xSize = 0;
    private final int maxMillimeter = 25;
    private final int FILTER_SIZE = 50;
    private int sampleRate = 8000 / FILTER_SIZE;
    private int gain = 5;
    private final int maxMidScopeY = 0;
    private double screenTotalTime;
    private int[] lineArray = new int[]{7321, 8521, 9600, 10875};
    private Map<Integer, Integer> lineMap = new HashMap();
//    private List<Float> xList = new ArrayList<>();


    public PdfEcgWaveView(Context context) {
        super(context);
        Log.d("caowj", "55555555555555555555555555");
        initPaint();
    }

    public PdfEcgWaveView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        Log.d("caowj", "66666666666666666666666666");
        initPaint();

    }

    public PdfEcgWaveView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        Log.d("caowj", "77777777777777777777777777");
        initPaint();

    }

    private void initPaint() {
        Log.d("caowj", "initPaint--------------");
        if (mPaint == null) {
            mPaint = new Paint();
            mPaint.setColor(Color.BLACK);
            mPaint.setAntiAlias(true);
            mPaint.setStrokeWidth(2);
            mPaint.setStrokeCap(Paint.Cap.ROUND);
            mPaint.setStyle(Paint.Style.STROKE);
        }
        if (mPaintLine == null) {
            mPaintLine = new Paint();
            mPaintLine.setColor(getContext().getResources().getColor(R.color.red));
            mPaintLine.setAntiAlias(true);
            mPaintLine.setStrokeWidth(2);
            mPaintLine.setStrokeCap(Paint.Cap.ROUND);
            mPaintLine.setStyle(Paint.Style.STROKE);
        }
    }

    @Override
    protected void onSizeChanged(int width, int height, int oldw, int oldh) {
        mHeight = getHeight();
        mCenterY = mHeight / 2;
        mWidth = getWidth();
//        Log.d("caowj", "onSizeChanged--------------"+mWidth+",,,"+mHeight+",,,"+mCenterY);

        zoom = height / maxMillimeter;
//        double speed = 0.04;
        double speed = (double) 2 / ((double) width / zoom);

        Log.e("caowj", "speed=" + speed);
        screenTotalTime = width / zoom * speed;
        gapX = (float) (this.mWidth / (sampleRate * screenTotalTime));
        xSize = Math.round(this.mWidth / gapX);
        points = new float[xSize * 4];
        Log.e("caowj", "初始化计算:zoom=" + zoom + ",screenTotalTime=" + screenTotalTime + ",gapX=" + gapX + ",widthSize=" + xSize);
        super.onSizeChanged(width, height, oldw, oldh);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        Log.d("caowj", "onMeasure--------------" + widthMeasureSpec + ",,," + heightMeasureSpec + ",,," + mCenterY);

        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        Log.w("caowj", "onDraw-----------" + pointList.size());
        len = pointList.size();
        if (len >= 2) {
            index = xSize - len;
//            Log.d("caowj", "drawCube  len=" + len + ",widthSize=" + widthSize + ",index=" + index);
            for (int i = index + 1; i < xSize; i++) {
                float startX = (i - 1) * gapX;
                int mIndex = i - index - 1;
                points[i * 4] = startX;
                points[i * 4 + 1] = pointList.get(mIndex);
                points[i * 4 + 2] = i * gapX;
                points[i * 4 + 3] = pointList.get(i - index);

                if (lineMap.containsKey(mIndex)) {
                    Log.w("caowj", "找到需要绘制竖线的位置了:" + startX);
//                    xList.add(startX);
                    int padding = SizeUtils.dp2px(getResources().getDimension(R.dimen.dp_25));
                    canvas.drawLine(startX, padding, startX, mCenterY * 2 - padding, mPaintLine);
                }
            }
        }

        canvas.drawLines(points, mPaint);

        super.onDraw(canvas);
    }


    public void addWaveDataInVisiable(short[] waveData) {
        if (nativeDatas == null) {
            nativeDatas = new ArrayList<>();
        }

        for (int i = 0; i < waveData.length; i++) {
            short y = (short) Math.floor(calcRealMv(maxMidScopeY - waveData[i]) * gain * zoom + mCenterY);
            nativeDatas.add(y);
//            Log.e("caowj", "y=" + y);
        }
        Log.e("caowj", "nativeDatas 长度=" + nativeDatas.size());
        if (nativeDatas.size() >= 800) {
            addPointThreadExecutor(nativeDatas);
            nativeDatas = new ArrayList<>();
        }
    }

    private void addPointThreadExecutor(List<Short> nativeDatas) {
        if (nativeDatas == null) {
            return;
        }

        List<Short> dataList = nativeDatas;
        synchronized (pointList) {
            for (int i = 0; i < dataList.size(); i += FILTER_SIZE) {
                if (pointList.size() >= xSize && xSize > 0) {
                    pointList.remove(0);
                }

                pointList.add(dataList.get(i));

                for (int linePosition : lineArray) {
                    if (linePosition > i - FILTER_SIZE && linePosition <= i) {
                        lineMap.put(pointList.size(), linePosition);
                    }
                }
            }
        }
    }


    public void clear() {
        if (pointList != null) {
            pointList.clear();
        }
        if (nativeDatas != null) {
            nativeDatas.clear();
        }

        points = new float[xSize * 4];
        postInvalidate();
    }


    /**
     * mintti  计算真实毫伏值
     *
     * @param point
     * @return
     */
    private float calcRealMv(int point) {
        return (float) (point * 3.3 / 32767);
//        int magnification = 1000;//TODO 放大倍数
//        return (float) (point / magnification * 3.3 / 32767 * 1000);
    }
}
css 复制代码
 public static void createWaveImage(Context context, ViewGroup parentView, AudioFile audioFile, String parentDir, String fileName, int index, boolean isLast) {
        Log.w("caowj", "createWaveImage");

        View rootView = LayoutInflater.from(context).inflate(R.layout.item_wave_view, null);
        PdfEcgWaveView waveView = rootView.findViewById(R.id.wave_view);
        TextView tvTitle = rootView.findViewById(R.id.tv_file_create_date);
        TextView tvIndex = rootView.findViewById(R.id.tv_index);
        tvIndex.setText("TL");
        String[] arr = fileName.split("\\.");
        String imageName = arr[0] + "(" + index + ")";
        String imgTitle = "";
        if (arr[0].startsWith("0_")) {
            imgTitle = StringUtils.getPositionAiResult(fileName);
        }
        if (TextUtils.isEmpty(imgTitle)) {
            imgTitle = imageName;
        }
        tvTitle.setText(imgTitle);

        int width = SizeUtils.getScreenWidth() * 2 / 3;
        int height = SizeUtils.dp2px(context.getResources().getDimension(R.dimen.dp_145));

        layoutView(rootView, width, height);

        audioFile.refreshPcmDataByPosition(index, 8000 * 2);
        waveView.addWaveDataInVisiable(audioFile.getData().clone());


        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        // 利用bitmap生成画布
        Canvas canvas = new Canvas(bitmap);
        // 把view中的内容绘制在画布上
        rootView.draw(canvas);// 触发draw()

        new Thread(new Runnable() {
            @Override
            public void run() {
                Log.d("caowj", "生成Bitmap");
                boolean result = FileUtils.saveWaveBitmap(bitmap, parentDir, imageName + ".jpg");
            }
        }).start();

    }

    protected static void layoutView(View v, int w, int h) {
        v.layout(0, 0, w, h);
        int measuredWidth = View.MeasureSpec.makeMeasureSpec(w, View.MeasureSpec.EXACTLY);
        int measuredHeight = View.MeasureSpec.makeMeasureSpec(h, View.MeasureSpec.EXACTLY);
        v.measure(measuredWidth, measuredHeight);
        Log.w("caowj", measuredWidth + "--" + measuredHeight + ";;;" + v.getMeasuredWidth() + "---" + v.getMeasuredHeight());
        v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight());
    }
相关推荐
且听真言1 天前
Flutter实现气泡提示框学习
path·自定义view·custompainter·rect·arrowlocation
且随疾风前行.16 天前
重学Android:自定义View基础(一)
android·自定义view
sziitjin3 个月前
IOS 03 纯代码封装自定义View控件
ios·自定义view
qq_289093873 个月前
自定义 View 可以播放一段视频
android·音视频·自定义view
cxylay3 个月前
【matlab版】如何利用代码计算声音信号的声压级
开发语言·matlab·代码·波形图·声压·声压级·声压级图
tracydragonlxy6 个月前
Android 实现竖排文本(垂直方向显示)
android·自定义view·textview·竖向文本·垂直文本
logan.gan7 个月前
AutoBackgroundBackButton 在ScrollView上方自动根据返回键按钮下方内容动态改变颜色。自动变色返回键
android·自定义view
qq_289093878 个月前
android 怎么自定义view
android·自定义view
芝麻粒儿1 年前
Android修行手册-超出父布局进行显示以及超出父布局实现点击
android·kotlin·自定义view