简体   繁体   English

Xamarin.Forms 设置自定义视图的大小

[英]Xamarin.Forms set size of custom view

How do I set the size, in xaml, of a custom view or, more specifically, a custom BoxView?如何在 xaml 中设置自定义视图或更具体地说是自定义 BoxView 的大小? Currently, the view takes up the entire device size instead of the requested 20x20.目前,视图占据了整个设备大小,而不是请求的 20x20。

在此处输入图片说明

Here's my xaml这是我的 xaml

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:Beltpack"
             xmlns:controls="clr-namespace:Beltpack.Views;assembly=Beltpack"
             x:Class="Beltpack.MainPage">

  <controls:bpButton Height="20" Width="20" HeightRequest="20" WidthRequest="20" />

</ContentPage>

My button deriving from BoxView (currently doesn't do anything)我从 BoxView 派生的按钮(目前没有做任何事情)

using Xamarin.Forms;

namespace Beltpack.Views {
    public class bpButton : BoxView {

        public bpButton() { }

    }

}

And my custom renderer还有我的自定义渲染器

using Android.Graphics;
using Xamarin.Forms.Platform.Android;
using Xamarin.Forms;
using Beltpack.Views;
using Beltpack.Droid;

[assembly: ExportRenderer(typeof(bpButton), typeof(bpButtonRenderer))]

namespace Beltpack.Droid {
    public class bpButtonRenderer : BoxRenderer {

        public bpButtonRenderer() {}

        protected override void OnDraw(Canvas canvas) {
            bpButton btn = (bpButton)this.Element;

            Paint paint = new Paint();
            paint.Color = Android.Graphics.Color.Aqua;

            canvas.DrawCircle((int)(btn.WidthRequest * .5), (int)(btn.HeightRequest * .5), (int)(btn.WidthRequest * .5), paint);
        }        
    }
}

In addition to setting WidthRequest and HeightRequest , you must also set your HorizontalOptions and VerticalOptions settings.除了设置WidthRequestHeightRequest ,您还必须设置HorizontalOptionsVerticalOptions设置。

Why?为什么? I have no clue, but that has been the solution suggested elsewhere and has consistently worked for me.我不知道,但这是其他地方建议的解决方案,并且一直对我有用。

It looks like you want it in the center, so you could simply write看起来你想要它在中心,所以你可以简单地写

<controls:bpButton 
    Height="20"
    Width="20" 
    HeightRequest="20"
    WidthRequest="20"
    HorizontalOptions="Center"
    VerticalOptions="Center" />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM