我设法在 TextureView 上显示相机流,并制作一个位图来读取流中每一帧的像素。然后我可以应用跟踪算法来跟踪一个球。但是现在,我想显示一个红色标记(例如),它显示找到的球的位置。我该怎么做?
最佳答案
我相信有很多方法可以在相机 View 上绘制标记。这里我使用了一个SurfaceView
。基本思想是在 Textureview
的顶部设置一个具有透明背景的 SurfaceView
。
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextureView android:id="@+id/textureView"
android:layout_height="match_parent"
android:layout_width="match_parent" />
<SurfaceView
android:id="@+id/surfaceview"
android:layout_height="match_parent"
android:layout_width="match_parent" />
</RelativeLayout >
代码隐藏:
public class MainActivity : Activity, TextureView.ISurfaceTextureListener
{
private Android.Hardware.Camera _camera;
private TextureView _textureView;
private SurfaceView _surfaceView;
private ISurfaceHolder holder;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
_textureView = (TextureView)FindViewById(Resource.Id.textureView);
_textureView.SurfaceTextureListener = this;
_surfaceView = (SurfaceView)FindViewById(Resource.Id.surfaceview);
//set to top layer
_surfaceView.SetZOrderOnTop(true);
//set the background to transparent
_surfaceView.Holder.SetFormat(Format.Transparent);
holder = _surfaceView.Holder;
_surfaceView.Touch += _surfaceView_Touch;
}
private void _surfaceView_Touch(object sender, View.TouchEventArgs e)
{
//define the paintbrush
Paint mpaint = new Paint();
mpaint.Color = Color.Red;
mpaint.SetStyle(Paint.Style.Stroke);
mpaint.StrokeWidth = 2f;
//draw
Canvas canvas = holder.LockCanvas();
//clear the paint of last time
canvas.DrawColor(Color.Transparent, PorterDuff.Mode.Clear);
//draw a new one, set your ball's position to the rect here
var x = e.Event.GetX();
var y = e.Event.GetY();
Rect r = new Rect((int)x, (int)y, (int)x + 100, (int)y + 100);
canvas.DrawRect(r, mpaint);
holder.UnlockCanvasAndPost(canvas);
}
public bool OnSurfaceTextureDestroyed(SurfaceTexture surface)
{
_camera.StopPreview();
_camera.Release();
return true;
}
public void OnSurfaceTextureAvailable(SurfaceTexture surface, int width, int height)
{
_camera = Android.Hardware.Camera.Open();
try
{
_camera.SetPreviewTexture(surface);
_camera.SetDisplayOrientation(90);
_camera.StartPreview();
}
catch (Java.IO.IOException ex)
{
Console.WriteLine(ex.Message);
}
}
public void OnSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height)
{
}
public void OnSurfaceTextureUpdated(SurfaceTexture surface)
{
}
}
因为我没有跟踪球的跟踪算法,我使用了 SurfaceView
的 Touch
事件,每次当你点击 SurfaceView
,点击的位置会绘制一个红色描边的矩形。您可以将我的_surfaceView_Touch
方法中的代码修改为您的跟踪算法并绘制您的红色标记。
关于c# - 如何使用 Xamarin.Android 在相机流上绘制标记?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42273981/