我正在设计一个屏幕,屏幕顶部有一个按钮,中间有一个画布,屏幕底部还有一些按钮。这是我目前的布局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button
android:text="Button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/button1" />
<View
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/iv_view1"
android:layout_marginBottom="0.0dp" />
<Button
android:text="Button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/button2" />
</LinearLayout>
在我的主要活动中,我尝试了这个:
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.Main);
var view = FindViewById<View>(Resource.Id.iv_view1);
var canvasView = new MyCanvas(this.BaseContext);
view = canvasView;
}
然而,结果并不像预期的那样。仅显示顶部按钮,并且未显示我在画布上绘制的图像。问题不在于画布,因为我已经单独测试了它作为全屏视图,并且它可以工作。这是我的画布代码,以防万一:
public class MyCanvas : View
{
private readonly ShapeDrawable _shape;
public MyCanvas(Context context) : base(context)
{
var paint = new Paint();
paint.SetARGB(255, 200, 255, 0);
paint.SetStyle(Paint.Style.Stroke);
paint.StrokeWidth = 4;
_shape = new ShapeDrawable(new OvalShape());
_shape.Paint.Set(paint);
_shape.SetBounds(20, 20, 300, 200);
}
protected override void OnDraw(Canvas canvas)
{
_shape.Draw(canvas);
}
}
答案 0 :(得分:1)
像这样修改你的MyCanvas
:
public class MyCanvas : View
{
private ShapeDrawable _shape;
public MyCanvas(Context context) : this (context, null)
{
}
public MyCanvas(Context context, IAttributeSet attrs) : this (context, attrs, 0)
{
}
public MyCanvas(Context context, IAttributeSet attrs, int defStyle) : base (context, attrs, defStyle)
{
Init();
}
public void Init()
{
var paint = new Paint();
paint.SetARGB(255, 200, 255, 0);
paint.SetStyle(Paint.Style.Stroke);
paint.StrokeWidth = 4;
_shape = new ShapeDrawable(new OvalShape());
_shape.Paint.Set(paint);
_shape.SetBounds(20, 20, 300, 200);
}
protected override void OnDraw(Canvas canvas)
{
_shape.Draw(canvas);
}
}
然后您可以在axml
文件中使用它,就像常见的视图一样,例如:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button
android:text="Button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/button1" />
<!-- Replace Your_MyCanvas_Namespace with the namespace of your MyCanvas class -->
<Your_MyCanvas_Namespace.MyCanvas
android:layout_width="wrap_content"
android:layout_height="100dp"
android:id="@+id/iv_view1"
/>
<Button
android:text="Button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/button2" />
</LinearLayout>
在MainActivity
:
MyCanvas myCanvas = FindViewById<MyCanvas>(Resource.Id.iv_view1);
效果: