How to compute aspect using metal-cpp

Hi, I am experimenting with the 05-perspective.cpp code in LearnMetalCPP. I have made the window resizable by dragging an edge or corner with the mouse. But this causes the image to distort because the original drawing was square and the aspect set to 1.0. Now I want to compute aspect = width/height to use in simd::float4x4 makePerspective( float fovRadians, float aspect, float znear, float zfar ) in the 05-perspective.cpp app. What is the best way to get width and height, such as from CGSize.width and CGSize.height?

Replies

Hi raw915,

From the CA::MetalDrawable you can access the view's CA::MetalLayer. This layer exposes method drawableSize(), which returns a CGSize you can use to determine the width and height of the layer. Use these values to compute the aspect ratio of your view and adjust your projection matrix accordingly.

For example, the following code in your draw loop should print the width and height of the layer as you resize it.

CGSize siz = pDrawable->layer()->drawableSize();
printf("%.2f, %.2f\n", siz.width, siz.height);