Get element position after transform

醉酒当歌 提交于 2019-12-18 02:54:12

问题


I have a UIElement that has various transformations performed on it (scale and translate).

Is there a way to get the UIElement's position after transformation? I tried GetValue(Canvas.TopProperty) but it doesn't change from what it was loaded as.

I must be missing something obvious but not sure what. (I'm using silverlight)


回答1:


It is a little bit unintuitive to do this, but it can be done. It is a two step process. First, what you want to use the TransformToVisual function (from MSDN):

Returns a transform object that can be used to transform coordinates from the UIElement to the specified object.

TransformToVisual will yield a GeneralTransform that will perform the transformation from any UIElement to any other UIElement (given that they both exist in the same visual tree). It sounds like what you want is the transformation from the RootVisual.

var transform = Application.RootVisual.TransformToVisual(myUiElement);

The transform object is now a general transformation that can be used to transform anything in the same way that myUiElement was transformed relative to RootVisual

The next step is to transform a point using that transformation.

var myUiElementPosition = transform.Transform(new Point(0,0));

The myUiElementPosition is now a Point that has been transformed and should be the position of the UIElement you're looking for. new Point(0,0) is used because I assume you want to have the position given relative to the top left corner of the RootVisual.




回答2:


Try using this approach:

var offset = Application.RootVisual.TransformToVisual(myObject)
                                   .Transform(new Point(0,0));

TransformToVisual




回答3:


EDIT:

ok how about this ?

myObjectTransform.GetValue(CompositeTransform.TranslateXProperty)

and

myObjectTransform.GetValue(CompositeTransform.TranslateYProperty)


来源:https://stackoverflow.com/questions/5266506/get-element-position-after-transform

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!