简体   繁体   English

将 Xamarin.Forms 元素旋转 90 度(横向显示,无需旋转整个页面或设备)

[英]Rotate Xamarin.Forms element by 90 degrees (display in landscape without rotating the whole page or device)

Just one element on a page, like a grid with its sub-elements, should be rotated by 90 degrees while beeing normally aligned by its surrounding stacklayouts and so on.页面上只有一个元素,例如带有子元素的网格,应旋转 90 度,同时通过其周围的堆栈布局等正常对齐。

There is a Rotation="90" attribute.有一个Rotation="90"属性。 It works, but alignment seems to be calculated by its original orientation and the now exchanged height and width is not considered.它可以工作,但 alignment 似乎是按其原始方向计算的,并且不考虑现在交换的高度和宽度。 So, if the element wasn't a square, it now overlaps other elements or draws partially outside the screen.因此,如果元素不是正方形,它现在会与其他元素重叠或部分绘制在屏幕之外。 This doesn't make much sense to me.这对我来说没有多大意义。 How to do it right?怎么做才对?

Put the element into a RelativeLayout , where you can position elements freely.将元素放入RelativeLayout ,您可以在其中自由地 position 元素。

<RelativeLayout>
  <Grid Rotation="90" AnchorX="0" AnchorY="0"
        RelativeLayout.HeightConstraint="{ConstraintExpression Type=RelativeToParent, Property=Width}"
        RelativeLayout.WidthConstraint="{ConstraintExpression Type=RelativeToParent, Property=Height}"
        RelativeLayout.XConstraint="{ConstraintExpression Type=RelativeToParent, Property=Width}">

  </Grid>
</RelativeLayout>

After exchanging just width and height, the element position is still wrong, because it is rotated around the original center ( AnchorX and Y default is 0.5 ).仅交换宽度和高度后,元素 position 仍然是错误的,因为它围绕原始中心旋转( AnchorXY默认为0.5 )。 This could be fixed by a translation by (Width - Height) / 2 (see code-behind solution below), but we get it much easier by changing the rotation anchor to one of its corners as seen above.这可以通过(Width - Height) / 2的平移来解决(参见下面的代码隐藏解决方案),但我们可以通过将旋转锚更改为它的一个角来更容易,如上所示。

/// <summary>
/// Rotates an element by 90 or 270 degrees. It is required that you put a RelativeLayout (no parameters needed)
/// around it and call this method on the element (i.e. in onAppearing).
/// </summary>
private void SetLandscape(VisualElement element, bool ccw = false)
{
    element.Rotation = ccw ? 270.0 : 90.0;
    RelativeLayout.SetHeightConstraint(element, Constraint.RelativeToParent(layout => layout.Width));
    RelativeLayout.SetWidthConstraint(element, Constraint.RelativeToParent(layout => layout.Height));
    RelativeLayout.SetYConstraint(element, Constraint.RelativeToParent(layout => (layout.Height - layout.Width) / 2));
    RelativeLayout.SetXConstraint(element, Constraint.RelativeToParent(layout => (layout.Width - layout.Height) / 2));
}

Both solutions keep working after layout changes on runtime.在运行时布局更改后,这两种解决方案都可以继续工作。

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

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