Getting the true visual bounding box of a WPF element? - wpf

For a simplified version of my problem, I would like to calculate the bounding box of a layout-transformed (possibly even render-transformed) shape, so that I can always fit a rectangle perfectly around the shape, no matter what its rotation or scale may be. If you can solve this, I will be happy.
The more complex problem is that of calculating the visual bounding box of any framework element. By 'visual bounding box' I mean the top-most visible pixel within the framework element determines the top-bound, the right-most visible pixel determines the right-bound, etc. If you can solve this, I will be even more happy.
I have tried playing with LayoutInformation.GetLayoutSlot(), but this did not work in the expected manner. The 'layout slot' was actually MUCH larger than the actual bounds. I also tried using VisualTreeHelper.GetDescendantBounds(), but because of the VisualParent of my test shape being protected I could not manage to access this property, and decided to check here before I go any further into it.
I hope that somebody can provide an easy way of getting the true visual bounding box of an element in WPF, that is calculated AFTER all transforms. If I have not made something clear in my question, please let me know.

private Rect GetRectOfObject(FrameworkElement _element)
{
Rect rectangleBounds = _element.RenderTransform.TransformBounds(
new Rect(_element.RenderSize);
return rectangleBounds;
}
Maybe this will help out.

You will get good results with VisualTreeHelper.GetDescendantBounds() and you can use VisualTreeHelper.GetParent() to gain access to the otherwise protected VisualParent property. However what you probably want to do is call GetDescendantBounds on the shape itself, not its parent, because in spite of its name, the method returns the bounds of the parent and all of its decendants.

The problem is not easy, as a control may draw outside its bounds.
But if you assume this doesn't happen you can solve the problem by using parent.TranslatePoint(point_in_child_coord_system, child) to transform (0,0), (child.ActualWidth,0), (child.ActualWidth, child.ActualHeight) and (0,child.ActualHeight) to the parent coord system. Then sort the x and y coordinates of all points and use minimum and maximum values to find the bounding box.
Note: sorting is necessary because of possible child rotation.

Related

How to find out if the surface detected by ARKit is no more available?

I am working on an application with ARKit and SceneKit frameworks. In my application I have enabled surface detection (I followed the placing objects sample provided by Apple). How to find if the surface detected is no more available? That is, initially only if user has detected the surface in ARSession I am allowing him to place the 3D object.
But if the user moves rapidly or focuses somewhere, the detected surface area is getting lost. In this case if the user tries to place another object I shouldn't allow him to place it until he scans the floor again and get the surface corrected.
Is there any delegate which is available to let us know that the surface detected is no more available?
There are delegate functions that you can use. The delegate is the ARSCNViewDelegate
It has a function that is renderer(_:didRemove:for:) that fires when an ARAnchor has been removed. You can use this function to perform some operation when a surface gets removed.
ARSCNViewDelegate Link
There are two ways to “lose” a surface, so there’s more than one approach to dealing with such a problem.
As noted in the other answer, there’s an ARSCNViewDelegate method that ARKit calls when an anchor is removed from the AR session. However, ARKit doesn’t remove plane anchors during a running session — once it’s detected a plane, it assumes the plane is always there. So that method gets called only if:
You remove the plane anchor directly by passing it to session.remove(anchor:), or
You reset the session by running it again with the .removeExistingAnchors option.
I’m not sure the former is a good idea, but the latter is important to handle, so you probably want your delegate to handle it well.
You can also “lose” a surface by having it pass out of view — for example, ARKit detects a table, and then the user turns around so the camera isn’t pointed at or near the table anymore.
ARKit itself doesn’t offer you any help for dealing with this problem. It gives you all the info you need to do the math yourself, though. You get the plane anchor’s position, orientation, and size, so you can calculate its four corner points. And you get the camera’s projection matrix, so you can check for whether any point is in the viewing frustum.
Since you’re already using SceneKit, though, there are also ways to get SceneKit to do the math for you... Working backwards:
SceneKit gives you an isNode(_:insideFrustumOf:) test, so if you have a SCNNode whose bounding box matches the extent of your plane anchor, you can pass that along with the camera (view.pointOfView) to find out if the node is visible.
To get a node whose bounding box matches a plane anchor, implement the ARSCNViewDelegate didAdd and didUpdate callbacks to create/update an SCNPlane whose position and dimensions match the ARPlaneAnchor’s center and extent. (Don’t forget to flip the plane sideways, since SCNPlane is vertically oriented by default.)
If you don’t want that plane visible in the AR view, set its materials to be transparent.

Zooming into a Canvas without modifying the size of specific child controls

So I realize that I am venturing outside of the intended use of a Canvas here and will likely have to come up with a more manual solution. However, not being overly experienced in WPF I was hoping that there may be some solution which would allow me to continue using a Canvas control and the features it gives you for free.
The issue revolves around a Canvas which is used to zoom in and out of an image and some number of child controls that belong to the Canvas. These child controls are to be placed at various positions on the image and, as such, the Canvas works nicely in that it handles all of the layout/positioning for me as I zoom in or out.
However, one drawback is that the Canvas scales these child controls up as I zoom into the image, causing them to become too large to be usable in practice. What I am looking for is a solution that allows me to zoom into an image that belongs to a canvas without also zooming up the size of the child controls, preferably handling the layout for me.
I have tried modifying the width and height of these child controls as the zoom factor increases or decreases, but there is a slight lag time and it all looks a bit 'jerky'.
If it comes down to it I will simply do all of the zooming/panning/layout myself, but I thought I would ask first just to make sure that I am not missing anything that would allow me to tell the Canvas to not scale the size of certain controls. Thanks in advance.
You can bind the children's RenderTransform to the inverse of the Canvas' transform, see my answer to this similar question on rotation.
This is more of a thought than an answer, but what if you set a transform on the element that you did not want scaled that was the opposite of the canvas itself. So for example, if the canvas had a scale transform of 2.0, set the element to have a scale transform of 0.5. You could probably accomplish this by binding the transform values together using a value converter.
You'll probably want to make sure the element has a render transform origin of 0.5,0.5 so that it scales from the center.

Check for overlapping shapes in WPF

I have a set of shapes which need to be drawn on top of each other. I need to re-order them such that the smallest shape gets drawn last (i.e. it will be closest to the user). Is there any way to check whether a shape overlappes (encloses and/or intersects) another shape. I know there is a method in Rect structure called Contains which checks whether there is an object within it. Is there a similar method or a way to simulate it on Shapes in WPF? Thanks in advance for any help.
Cheers,
Nilu
You could probably use the Geometry.FillContainsWithDetail method. Its name is ill-chosen IMHO, but the description is clear :
Returns a value that describes the intersection between the current geometry and the specified geometry.
I have successfully used it for collision testing before, so it should work for you too...

Best way to write a custom gauge control in WPF?

I need to write a gauge control in WPF for a project at work. By gauge control, I mean something akin to a traditional car speedometer: a circular face with numbers and ticks around the circumference, and a needle pointing to the current value. Although I could get my employer to purchase a third-party control, or even find a free one somewhere, I’d still like to write it myself, for curiosity’s sake more than anything else.
My first thought was to ‘skin’ an existing control using a template, something like a ProgressBar for example as it has Minimum, Maximum and Value properties. However, I don’t think this will offer me the flexibility that I need.
I’d like to animate the needle that points to the current value, so that when the gauge’s value changes the needle moves from the old value to the new value. I figured the easiest way to do this would be to have some kind of shape or geometry representing the needle, and then apply a RotateTransform of the relevant number of degrees to get the needle to point to the correct value. The animation’s To property would be set to the ‘value degrees’ property via binding.
It seems to me that there are three basic approaches I could take:
Use one custom FrameworkElement to represent the entire gauge
I could derive from FrameworkElement, override its OnRender method, then use the DrawingContext to draw both the gauge face and the needle. This would mean that I could no longer animate the needle directly using a RotateTransform, but would instead have to redraw the entire gauge every time the value changes. This seems inefficient to me, as the gauge face represents the bulk of the drawing code but would change very rarely. However, this approach is the most lightweight in terms of the number of elements used.
Use two custom FrameworkElements, one for the face and one for the needle
I’m currently leaning towards this approach. One element would represent the face, the other the needle. This would allow me to target the needle element with the RotateTransform. The gauge control would then consist of three elements: the face, the needle, and a Panel container to hold both of them (ie. Canvas, Grid, whatever). So three elements instead of one, hence not as lightweight as the first approach.
Use DrawingVisuals to draw the face and needle
I’ve also read about the DrawingVisual class, but I’m a bit confused as to why anyone would use this as opposed to deriving from FrameworkElement and overriding OnRender, given that DrawingVisual must be hosted in a custom FrameworkElement anyway. It would seem that this approach doesn’t offer any advantages over the second approach, and would require more code, but maybe I’m missing something.
Any thoughts or advice regarding which approach people think is best and why would be most welcome!
Personally I'd recommend making a CustomControl using the second approach. Unless you are going to be showing more than 1000 of the gauges in view at the same time you aren't going to notice the extra element in your visual tree and I think you'll find it's much easier to make and maintain.
You could just style a slider control and feed values into it. You should be able to make a slider look like any kind of gauge you need.

WPF 3D Billboards

In a 3D scene we often need to apply labels (little textelements or icons) next to 3D object that is moving around (rotation, translation) in the scene. These labels should always face the camera but still move with the object. This technique I believe is called billboard.
An additional cool feature would be if the label would stay always at the same size - no matter how far away the associated object is. So the label seems to live in 2D screenspace and not in the 3D scenegraph.
Does anyone figures out a clever way how to do this in WPF?
For billboarding you need to make sure that the face normal is pointing towards the camera. The algorithm is that the dot product between the face normal and the view direction should be -1 (minus one).
I have some old C code that does this, but it's probably not particularly useful.
For keeping the object the same size you'd need to work out the screen size and then apply a transform to keep it the constant size you desired.
However, if you want the object to appear as though it's in 2D space, why not draw it in a 2D overlay? This will solve both the billboarding and scaling problem at the same time. You work out the screen location of your label and then use the 2D drawing functions.

Resources