使用Surface View来显示图片
public class YUVImageView extends SurfaceView {
private static final String TAG = "YUVImageView";
private SurfaceHolder surfaceHolder;
private Paint paint;
private Rect srcRect, destRect;
private Canvas canvas;
private Bitmap bitmap;
private BitmapFactory.Options options;
private SurfaceHolder.Callback callback = new SurfaceHolder.Callback() {
@Override
public void surfaceCreated(SurfaceHolder holder) {
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
};
public YUVImageView(Context context) {
this(context, null);
}
public YUVImageView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public YUVImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initView();
}
private void initView() {
surfaceHolder = getHolder();
surfaceHolder.setFixedSize(640, 480);
surfaceHolder.addCallback(callback);
setZOrderOnTop(true);
setZOrderMediaOverlay(true);
paint = new Paint();
paint.setAntiAlias(true);
paint.setStyle(Paint.Style.STROKE);
srcRect = new Rect(0, 0, 640, 480);
destRect = new Rect(0, 0, 640, 480);
options = new BitmapFactory.Options();
}
public void drawBitmap(int id){
if (surfaceHolder != null) {
canvas = surfaceHolder.lockCanvas();
}
if (surfaceHolder != null && canvas != null) {
try {
canvas.drawColor(Color.WHITE);
bitmap = BitmapFactory.decodeResource(getResources(),id);
if (bitmap != null) {
canvas.drawBitmap(bitmap, srcRect, destRect, paint);
} else {
LogUtils.d(TAG, "create bitmap from yuvData array failed");
}
} catch (Exception e) {
e.printStackTrace();
LogUtils.e(TAG, "drawYUV error ", e);
} finally {
if (canvas != null && surfaceHolder != null) {
surfaceHolder.unlockCanvasAndPost(canvas);
}
if (bitmap != null) {
bitmap.recycle();
}
}
}
}
public void drawYUV(byte[] yuvData) {
if (surfaceHolder != null) {
canvas = surfaceHolder.lockCanvas();
}
if (surfaceHolder != null && canvas != null) {
try {
canvas.drawColor(Color.WHITE);
bitmap = BitmapFactory.decodeByteArray(yuvData, 0, yuvData.length, options);
if (bitmap != null) {
canvas.drawBitmap(bitmap, srcRect, destRect, paint);
} else {
LogUtils.d(TAG, "create bitmap from yuvData array failed");
}
} catch (Exception e) {
e.printStackTrace();
LogUtils.e(TAG, "drawYUV error ", e);
} finally {
if (canvas != null && surfaceHolder != null) {
surfaceHolder.unlockCanvasAndPost(canvas);
}
if (bitmap != null) {
bitmap.recycle();
}
}
}
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】