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

效果图:
在这里插入图片描述

页面布局:

<?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>

自定义波形图控件:

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);
    }
}
 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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
A:您可以使用ViewGroup配合ImageView和TextView自定义一个带有图片的单选框: 1. 新建一个布局文件 custom_radio.xml,定义一个LinearLayout作为容器,内嵌一个ImageView和TextView,分别用来显示选中和未选中状态的图片和文字: ``` <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal"> <ImageView android:id="@+id/radio_btn" android:layout_width="20dp" android:layout_height="20dp" android:layout_marginRight="8dp" android:src="@drawable/radio_unchecked"/> <TextView android:id="@+id/radio_text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="RadioButton"/> </LinearLayout> ``` 2. 在Java代码中创建一个自定义RadioGroup,并且遍历所有的custom_radio子View,设置点击事件和状态: ``` public class CustomRadioGroup extends LinearLayout implements View.OnClickListener { private int mCheckedId = -1; public CustomRadioGroup(Context context) { this(context, null); } public CustomRadioGroup(Context context, AttributeSet attrs) { super(context, attrs); setOrientation(VERTICAL); } @Override public void onClick(View v) { if (mCheckedId != v.getId()) { setCheckedState(v.getId()); mCheckedId = v.getId(); } } public int getCheckedId() { return mCheckedId; } public void setCheckedId(int id) { if (mCheckedId != id) { mCheckedId = id; setCheckedState(mCheckedId); } } private void setCheckedState(int id) { for (int i = 0; i < getChildCount(); i++) { View child = getChildAt(i); if (child instanceof ViewGroup) { ViewGroup group = (ViewGroup) child; ImageView btn = group.findViewById(R.id.radio_btn); if (group.getId() == id) { btn.setImageResource(R.drawable.radio_checked); } else { btn.setImageResource(R.drawable.radio_unchecked); } } } } public void addRadio(View view) { view.setId(View.generateViewId()); view.setOnClickListener(this); addView(view); } } ``` 3. 在 Activity 中使用自定义RadioGroup,并添加custom_radio子View: ``` CustomRadioGroup radioGroup = findViewById(R.id.custom_radio_group); LayoutInflater inflater = LayoutInflater.from(this); View view1 = inflater.inflate(R.layout.custom_radio, null); TextView textView1 = view1.findViewById(R.id.radio_text); textView1.setText("Radio1"); View view2 = inflater.inflate(R.layout.custom_radio, null); TextView textView2 = view2.findViewById(R.id.radio_text); textView2.setText("Radio2"); radioGroup.addRadio(view1); radioGroup.addRadio(view2); ``` 这样就完成了一个自定义的带有图片的单选框。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值