android视频加载预览图

package demo.pplive.com.imagepoint;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.CountDownTimer;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.animation.AlphaAnimation;

/**
 * @Createdby : jixiongxu
 * @on :2017/10/31
 * @description :显示进度条的视频预览,用户在选择快进的时候显示出快进的点的视频截图
 * @problem 目前存在的问题是内存一直在抖动,现在尚未解决,希望在真是使用过程将图片压缩后可以解决
 */

public class ImagePointView extends View
{

    private static final String TAG = "ImagePointView";

    // 最大X长度
    private static final int MAX_X = 200;

    // 最大Y长度
    private static final int MAX_Y = 120;

    // 最小X长度
    private static final int MIN_X = 50;

    // 最小Y长度
    private static final int MIN_Y = 30;

    // scaleType 16:9
    public static final int SCALETYPE_W16_H9 = 1;

    // scaleType 4:3
    public static final int SCALETYPE_W4_H3 = 0;

    // 默認padding
    private static final int defaultPadding = 3;

    private float density;

    // 图片地址
    private String mUrl;

    // 需要画的图片
    private Bitmap mSrc;

    // 默认的图片
    private Bitmap mDefaultSrc;

    // 宽度
    private int width;

    // 高度
    private int height;

    // 下边三角形的高度
    private int angleHeight = 5;

    // 16:9
    private float W16_H9_SCALE = 1.77777f;

    // 4:3
    private float W4_H3_SCALE = 1.33333f;

    // 0表示4:3,1表示16:9
    private int mScaleType = SCALETYPE_W16_H9;

    private int mPadding = defaultPadding;

    // 是测量用的,为了避免内存抖动drawableToBitmap

    private int w;

    // 是测量用的,为了避免内存抖动drawableToBitmap
    private int h;

    // 是测量用的,为了避免内存抖动drawableToBitmap
    private Bitmap bitmap;

    // 是测量用的,为了避免内存抖动drawableToBitmap
    private Bitmap.Config config;

    // 是测量用的,为了避免内存抖动drawableToBitmap
    private Canvas canvas;

    private Context mContext;

    // 倒计时,为了自动消失
    private CountDownTimer timer;

    private Paint mBackGroundPaint = new Paint();

    private Paint mImagePaint = new Paint();

    private Paint mAnglePaint = new Paint();

    private Rect size = new Rect();

    private Path mPath = new Path();

    private AlphaAnimation alpha = new AlphaAnimation(1.0f, 0f);

    public ImagePointView(Context context)
    {
        super(context);
        mContext = context;
        initView();
    }

    public ImagePointView(Context context, AttributeSet attrs)
    {
        super(context, attrs);
        initView();
    }

    public ImagePointView(Context context, AttributeSet attrs, int defStyleAttr)
    {
        super(context, attrs, defStyleAttr);
        initView();
    }

    private void initView()
    {
        alpha.setDuration(2000);
        alpha.setFillAfter(true);
    }

    // 3秒后开始消失,消失时间是2秒
    private void autoDismiss()
    {
        if (timer != null)
        {
            try
            {
                timer.cancel();
                timer.start();
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
        else
        {
            timer = new CountDownTimer(5000, 1000)
            {
                @Override
                public void onTick(long l)
                {
                    if (l < 2000)
                    {
                        setAnimation();
                    }
                }

                @Override
                public void onFinish()
                {
                    dismiss();
                }
            };
            timer.start();
        }
    }

    private void recycle()
    {

    }

    public void setAnimation()
    {
        this.startAnimation(alpha);
    }

    public void dismiss()
    {
        if (this.getVisibility() != GONE)
        {
            this.setVisibility(GONE);
        }
    }

    private void show()
    {
        if (this.getVisibility() != VISIBLE)
        {
            Log.d("jixiongxu", "show");
            this.setVisibility(VISIBLE);
        }
    }

    // 预留接口
    public void setUrl(String url)
    {
        if (url == null || url.isEmpty())
        {
            return;
        }
        mUrl = url;
    }
    // 预留接口
    public void setDefaultPadding(int padding)
    {
        mPadding = padding;
    }

    public void setScaleType(int type)
    {
        mScaleType = type;
    }

    public void setBitmap(Bitmap src)
    {
        if (src == null)
        {
            return;
        }
        mSrc = src;
        invalidate();
        show();
        autoDismiss();
    }

    public void setDefaultSrc(Bitmap def)
    {
        if (def == null)
        {
            return;
        }
        mDefaultSrc = def;
    }
    // 预留接口
    private Bitmap drawableToBitmap(Drawable drawable)
    {
        // 取 drawable 的长宽
        w = drawable.getIntrinsicWidth();
        h = drawable.getIntrinsicHeight();

        // 取 drawable 的颜色格式
        config = drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
        // 建立对应 bitmap
        bitmap = Bitmap.createBitmap(w, h, config);
        // 建立对应 bitmap 的画布
        canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, w, h);
        // 把 drawable 内容画到画布中s
        drawable.draw(canvas);
        return bitmap;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
    {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int mWidth = MeasureSpec.getSize(widthMeasureSpec);
        int mHeight = MeasureSpec.getSize(heightMeasureSpec);

        Log.d("TAG", "" + mWidth);
        Log.d("TAG", "" + mHeight);

        density = getResources().getDisplayMetrics().density;

        if (mWidth > MAX_X)
        {
            width = MAX_X;
        }
        if (mWidth < MIN_X)
        {
            width = MIN_X;
        }
        if (mHeight > MAX_Y)
        {
            height = MAX_Y;
        }
        if (mHeight < MIN_Y)
        {
            mHeight = MIN_Y;
        }

        mPadding = (int) (density * defaultPadding);

        // 缩放标准
        w = (int) Math.min(width * density, mWidth);
        h = (int) Math.min(height * density, mHeight);
        int scaleTemp = Math.min(w, h);

        if (mScaleType == SCALETYPE_W16_H9)
        {
            if (scaleTemp == w)
            {
                width = scaleTemp;
                height = (int) (scaleTemp / W16_H9_SCALE);
            }
            else if (scaleTemp == h)
            {
                height = scaleTemp;
                width = (int) (scaleTemp * W16_H9_SCALE);
            }
        }
        else if (mScaleType == SCALETYPE_W4_H3)
        {
            if (scaleTemp == w)
            {
                width = scaleTemp;
                height = (int) (scaleTemp / W4_H3_SCALE);
            }
            else if (scaleTemp == h)
            {
                height = scaleTemp;
                width = (int) (scaleTemp * W4_H3_SCALE);
            }
        }
        size.set(mPadding, mPadding, width - mPadding, height - mPadding);
        setMeasuredDimension(width, (int) (height + angleHeight * density));
    }

    @Override
    protected void onDraw(Canvas canvas)
    {
        super.onDraw(canvas);
        DrawBackGround(canvas);
        DrawImage(canvas);
        DrawAngle(canvas);
    }

    // 先画背景
    private void DrawBackGround(Canvas canvas)
    {
        // 画笔
        mBackGroundPaint.setColor(Color.WHITE);
        mBackGroundPaint.setStyle(Paint.Style.FILL);
        canvas.drawRect(0, 0, width, height, mBackGroundPaint);
    }

    // 再画图片
    private void DrawImage(Canvas canvas)
    {
        // 画笔
        mImagePaint.setStyle(Paint.Style.FILL);

        if (mSrc != null)
        {
            canvas.drawBitmap(mSrc, null, size, mImagePaint);
        }
        else
        {
            Log.e(TAG, "image is null");
            if (mDefaultSrc != null)
            {
                canvas.drawBitmap(mDefaultSrc, null, size, mImagePaint);
            }
            else
            {
                Log.e(TAG, "default image is null");
            }
        }
    }

    // 最后画三角形
    private void DrawAngle(Canvas canvas)
    {
        mAnglePaint.setStyle(Paint.Style.FILL);
        // 全透明外框
        mAnglePaint.setColor(Color.argb(0, 0, 0, 0));
        canvas.drawRect(0, height, width, (int) (height + angleHeight * density), mAnglePaint);
        mAnglePaint.setStyle(Paint.Style.FILL);
        mAnglePaint.setColor(Color.WHITE);
        // 下面的三角形
        mPath.moveTo(width / 2 - angleHeight * density, height);
        mPath.lineTo(width / 2 + angleHeight * density, height);
        mPath.lineTo(width / 2, height + angleHeight * density);
        mPath.close();
        canvas.drawPath(mPath, mAnglePaint);
    }

    @Override
    public void dispatchWindowVisibilityChanged(int visibility)
    {
        super.dispatchWindowVisibilityChanged(visibility);

        if (visibility == GONE)
        {
            // dosomething
        }
        else if (visibility == VISIBLE)
        {
            // dosomething
        }
    }
}
//效果图

发布了5 篇原创文章 · 获赞 3 · 访问量 1万+
展开阅读全文

Android拍视频预览的界面被拉伸

06-02

最近 Android 需要做一个拍视频保存然后上传的功能,基本功能实现了,但是有一个小 bug,就是预览的时候界面明显被拉长了,但是各种预览设置的参数也都试过了,都没有用,来请教一下。 #代码如下: ##1. Activity ``` public class RecordActivity extends AppCompatActivity implements SurfaceHolder.Callback { private SurfaceView mSurfaceView; private SurfaceHolder mSurfaceHolder; private Button btnStartStop; private boolean isRecording = false; // 标记是否已经在录制 private MediaRecorder mRecorder; // 音视频录制类 private Camera mCamera = null; // 相机 private List<Camera.Size> mSupportedPreviewSizes = null; private Camera.Size mPreviewSize; private Camera.Size mSize = null;// 相机的尺寸 private int mCameraFacing = Camera.CameraInfo.CAMERA_FACING_BACK; // 默认后置摄像头 private static final SparseIntArray orientations = new SparseIntArray(); // 手机旋转对应的调整角度 static { orientations.append(Surface.ROTATION_0, 90); orientations.append(Surface.ROTATION_90, 0); orientations.append(Surface.ROTATION_180, 270); orientations.append(Surface.ROTATION_270, 180); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); initWindow(); setContentView(R.layout.activity_record); initViews(); } /** * 初始化窗口 */ private void initWindow() { requestWindowFeature(Window.FEATURE_NO_TITLE); // 去掉标题栏 getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); // 设置全屏 // 设置竖屏显示 setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); // 选择支持半透明模式,在有 surfaceView 的 activity 中使用。 getWindow().setFormat(PixelFormat.TRANSLUCENT); } /** * 视图对象初始化 */ private void initViews() { mSurfaceView = (SurfaceView) findViewById(R.id.surfaceview); btnStartStop = (Button) findViewById(R.id.btnStartStop); btnStartStop.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!isRecording) { startRecord(); } else { stopRecord(); } } }); SurfaceHolder holder = mSurfaceView.getHolder(); // 取得holder holder.setFormat(PixelFormat.TRANSPARENT); holder.setKeepScreenOn(true); holder.addCallback(this); // holder加入回调接口 } /** * 初始化相机 */ private void initCamera() { /** * 默认打开后置摄像头 */ if (Camera.getNumberOfCameras() == 2) { mCamera = Camera.open(mCameraFacing); } else { mCamera = Camera.open(); } CameraSizeComparator sizeComparator = new CameraSizeComparator(); Camera.Parameters parameters = mCamera.getParameters(); if (mSize == null) { mSupportedPreviewSizes = parameters.getSupportedPreviewSizes(); Collections.sort(mSupportedPreviewSizes, sizeComparator); for (int num = 0; num < mSupportedPreviewSizes.size(); num++) { Camera.Size size = mSupportedPreviewSizes.get(num); if (size.width >= 1000 && size.height >= 1000) { this.mSize = size; break; } } mSize = mSupportedPreviewSizes.get(0); /** * 增加对聚焦模式的判断 */ List<String> focusModesList = parameters.getSupportedFocusModes(); if (focusModesList.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO)) { parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO); } else if (focusModesList.contains(Camera.Parameters.FOCUS_MODE_AUTO)) { parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO); } mCamera.setParameters(parameters); } int rotation = getWindowManager().getDefaultDisplay().getRotation(); int orientation = orientations.get(rotation); mCamera.setDisplayOrientation(orientation); } @Override protected void onResume() { super.onResume(); initCamera(); } @Override public void onPause() { releaseCamera(); super.onPause(); } /** * 开始录制 */ private void startRecord() { if (mRecorder == null) { mRecorder = new MediaRecorder(); // 创建MediaRecorder } if (mCamera != null) { mCamera.stopPreview(); mCamera.unlock(); mRecorder.setCamera(mCamera); } try { // 设置音频采集方式 mRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER); // 设置视频的采集方式 mRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA); /* mRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4); // 设置文件的输出格式 mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); // 设置audio的编码格式 mRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264); // 设置video的编码格式 mRecorder.setVideoEncodingBitRate(10 * 1024 * 1024); // 设置录制的视频编码比特率 mRecorder.setVideoFrameRate(30); // 设置录制的视频帧率 mRecorder.setVideoSize(1920, 1080); // 设置相机分辨率 */ // 设置要捕获的视频的宽度和高度 // mSurfaceHolder.setFixedSize(optimalSize.width, optimalSize.height); mRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH)); // 设置记录会话的最大持续时间(毫秒) mRecorder.setMaxDuration(180 * 1000); mRecorder.setPreviewDisplay(mSurfaceHolder.getSurface()); /** * 获取外部路径,然后将视频保存进去 */ String path = Environment.getExternalStorageDirectory().getPath(); if (path != null) { File dir = new File(path + "/crafts_videos"); if (!dir.exists()) { dir.mkdir(); } /** * 将 currentTimeMillis() 作为文件名 */ path = dir + "/" + System.currentTimeMillis() + ".mp4"; mRecorder.setOutputFile(path); //设置输出文件的路径 mRecorder.prepare(); //准备录制 mRecorder.start(); //开始录制 isRecording = true; btnStartStop.setText("停止"); } } catch (Exception e) { e.printStackTrace(); } } /** * 停止录制 */ private void stopRecord() { try { mRecorder.stop(); // 停止录制 mRecorder.reset(); // 重置 btnStartStop.setText("开始"); } catch (Exception e) { e.printStackTrace(); } isRecording = false; } /** * 释放 MediaRecorder */ private void releaseMediaRecorder() { if (mRecorder != null) { mRecorder.release(); mRecorder = null; } } /** * 释放相机资源 */ private void releaseCamera() { try { if (mCamera != null) { mCamera.stopPreview(); mCamera.setPreviewCallback(null); mCamera.unlock(); mCamera.release(); } } catch (RuntimeException e) { } finally { mCamera = null; } } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { // 将holder,这个holder为开始在onCreate里面取得的holder,将它赋给mSurfaceHolder mSurfaceHolder = holder; if (mCamera == null) { return; } try { //设置显示 mCamera.setPreviewDisplay(holder); mCamera.startPreview(); } catch (Exception e) { e.printStackTrace(); releaseCamera(); finish(); } } @Override public void surfaceCreated(SurfaceHolder holder) { // 将holder,这个holder为开始在onCreate里面取得的holder,将它赋给mSurfaceHolder mSurfaceHolder = holder; try { mCamera.setPreviewDisplay(mSurfaceHolder); mCamera.startPreview(); } catch (IOException e) { e.printStackTrace(); } } @Override public void surfaceDestroyed(SurfaceHolder holder) { // surfaceDestroyed的时候同时对象设置为null if (isRecording && mCamera != null) { mCamera.lock(); } mSurfaceView = null; mSurfaceHolder = null; releaseMediaRecorder(); releaseCamera(); } private class CameraSizeComparator implements Comparator<Camera.Size> { public int compare(Camera.Size lhs, Camera.Size rhs) { if (lhs.width == rhs.width) { return 0; } else if (lhs.width > rhs.width) { return 1; } else { return -1; } } } } ``` ##2. 布局 ``` <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <SurfaceView android:id="@+id/surfaceview" android:layout_width="match_parent" android:layout_height="match_parent" /> <Button android:id="@+id/btnStartStop" android:layout_width="60dp" android:layout_height="40dip" android:layout_centerHorizontal="true" android:layout_alignParentBottom="true" android:text="开始" /> </RelativeLayout> ``` ##3. 权限 ``` <uses-permission android:name="android.permission.CAMERA" /> <uses-permission android:name="android.permission.RECORD_AUDIO" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> ``` 求大神解答 问答

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 编程工作室 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览