Rotate everything with SkiaSharp and Xamarin

In this post, I’m going to explain object rotation from the mathematical point of view and demonstrate different methods of how to draw rotated objects in SkiaSharp.

Rotation and Math

So, what is rotation? Usually, when someone says that he wants to rotate a figure, intuitively I think that the figure will stay at the same location and will be rotated around its center. But in fact, in computer graphics, that’s not quite correct. A rotation in computer graphics always happens around the origin, which is the point (0, 0).

Fig. 1 – Rotation of a point

Take a look at Figure 1. Point A (x, y) is rotated at angle θ around (0,0). The result is A'(x’,y’). Note that the length r does not change. With a little help of trigonometry, we can find that:
(1) x = r cos (α)
(2) y = r sin (α)
Similar is true for Point A’:
(3) x’ = r cos (α + θ)
(4) y’ = r sin (α + θ)
Using Ptolemy’s identities we can get:
(5) x’ = r cos (α) cos (θ) − r sin (α) sin (θ)
(6) y’ = r cos (α) sin (θ) + r sin (α) cos (θ)
And finally, we can substitute (1) and (2) into (5) and (6):
x’ = x cos (θ) – y sin (θ)
y’ = x sin (θ) + y cos (θ)
Knowing how to rotate a point, we can rotate any figure by applying the same transformation to all points of the figure.

Fig. 2 – Rotation of a rectangle

And finally to rotate a figure about an arbitrary point C (cx, cy), we should do three steps:

  1. Move (translate) the figure so the point C becomes a new origin. That can be achieved by subtracting cx, cy from all coordinates;
  2. Rotate the figure;
  3. Translate the figure back to the original position.
Fig. 3 – Rotation about an arbitrary point

 
At Figure 3 a rectangle is rotated at 90 degrees around point A (2,1).

Rotation and SkiaSharp

There are multiple ways to do a rotation in SkiaSharp. Let me demonstrate three of them. In the demo project, I’m going to rotate a square using

  1. Canvas methods;
  2. Manual approach;
  3. Transformation Matrices.

The point (0,0) is in the upper left corner of the screen and the y-axis grows downward, that’s why the objects rotate clockwise.

Fig. 4 Demo Project

Canvas methods

This is the easiest way to do a rotation.

void DrawRotatedUsingCanvas(SKCanvas canvas, SKPath path, SKPaint paint, float degrees, float cx, float cy)
{
    canvas.Save();
    canvas.RotateDegrees(degrees, cx, cy);
    canvas.DrawPath(path, paint);
    canvas.Restore();
}

We begin with saving the current canvas state and applying a rotation about a certain point. Anything drawn afterward will be rotated. Finally, we restore the initial canvas state.

Manual approach

We already reviewed the formulas to calculate new coordinates to rotate a point. Let’s use them to rotate an SKPath object that represents a square:

void DrawRotatedManually(SKCanvas canvas, SKPath path, SKPaint paint, float degrees, int cx, int cy)
{
    float rad = ToRadians(degrees);
    using (SKPath pathRotated = new SKPath())
    {
        pathRotated.MoveTo(Rotate(path[0], cx, cy, rad));
        pathRotated.LineTo(Rotate(path[1], cx, cy, rad));
        pathRotated.LineTo(Rotate(path[2], cx, cy, rad));
        pathRotated.LineTo(Rotate(path[3], cx, cy, rad));
        pathRotated.LineTo(Rotate(path[4], cx, cy, rad));
        canvas.DrawPath(pathRotated, paint);
    }
}
SKPoint Rotate(SKPoint point, int cx, int cy, float rad)
{
    var sin = (float)Math.Sin(rad);
    var cos = (float)Math.Cos(rad);
    var translatedX = point.X - cx;
    var translatedY = point.Y - cy;
    var rotatedX = translatedX * cos - translatedY * sin;
    var rotatedY = translatedX * sin + translatedY * cos;
    return new SKPoint(rotatedX + cx, rotatedY + cy);
}
static float ToRadians(float degrees)
{
    return (float)(Math.PI * degrees / 180.0);
}

The code here is self-explanatory. It’s good to understand the basics but probably there is no point to use it for production.

Transformation Matrices

Matrix Transform is a powerful technique that allows combining (concatenating) multiple transformations into a single one to significantly reduce complexity and number of calculations required to get new coordinates.

void DrawRotatedWithMatrices(SKCanvas canvas, SKPath path, SKPaint paint, float degrees, int cx, int cy)
{
    var result = SKMatrix.MakeIdentity();
    var translate = SKMatrix.MakeTranslation(-cx, -cy);
    var rotate = SKMatrix.MakeRotationDegrees(degrees);
    var translate2 = SKMatrix.MakeTranslation(cx, cy);
    SKMatrix.PostConcat(ref result, translate);
    SKMatrix.PostConcat(ref result, rotate);
    SKMatrix.PostConcat(ref result, translate2);
    path.Transform(result);
    canvas.DrawPath(path, paint);
}

The code above creates 4 matrices – one to hold the result and one for each transformation (translate, rotate, translate back), concatenates them and applies the transformation to the given path.

There is an overload of the SKMatrix.MakeRotationDegrees method that takes an arbitrary rotation point. We can get the desired rotation matrix with just one line of code, but for the sake of demonstration I’m not using it.

Conclusion

Here I have shown three different ways to draw a rotated object using SkiaSharp. For production, use canvas methods when you simply need to draw an object and use Transformation Matrices when you need a complex transformation or you want to know coordinates before drawing an object. Computer graphics is fun, happy coding everyone!
P.S.
I used a super-awesome free geometry tool to create images for this post: https://www.math10.com/en/geometry/geogebra/geogebra.html
The code of the demo project can be found here: https://github.com/vecalion/SkiaSharpRotationDemo
 

Related Blog Posts

We hope you’ve found this to be helpful and are walking away with some new, useful insights. If you want to learn more, here are a couple of related articles that others also usually find to be interesting:

Our Gear Is Packed and We're Excited to Explore With You

Ready to come with us? 

Together, we can map your company’s software journey and start down the right trails. If you’re set to take the first step, simply fill out our contact form. We’ll be in touch quickly – and you’ll have a partner who is ready to help your company take the next step on its software journey. 

We can’t wait to hear from you! 

Main Contact

This field is for validation purposes and should be left unchanged.

Together, we can map your company’s tech journey and start down the trails. If you’re set to take the first step, simply fill out the form below. We’ll be in touch – and you’ll have a partner who cares about you and your company. 

We can’t wait to hear from you! 

Montage Portal

Montage Furniture Services provides furniture protection plans and claims processing services to a wide selection of furniture retailers and consumers.

Project Background

Montage was looking to build a new web portal for both Retailers and Consumers, which would integrate with Dynamics CRM and other legacy systems. The portal needed to be multi tenant and support branding and configuration for different Retailers. Trailhead architected the new Montage Platform, including the Portal and all of it’s back end integrations, did the UI/UX and then delivered the new system, along with enhancements to DevOps and processes.

Logistics

We’ve logged countless miles exploring the tech world. In doing so, we gained the experience that enables us to deliver your unique software and systems architecture needs. Our team of seasoned tech vets can provide you with:

Custom App and Software Development

We collaborate with you throughout the entire process because your customized tech should fit your needs, not just those of other clients.

Cloud and Mobile Applications

The modern world demands versatile technology, and this is exactly what your mobile and cloud-based apps will give you.

User Experience and Interface (UX/UI) Design

We want your end users to have optimal experiences with tech that is highly intuitive and responsive.

DevOps

This combination of Agile software development and IT operations provides you with high-quality software at reduced cost, time, and risk.

Trailhead stepped into a challenging project – building our new web architecture and redeveloping our portals at the same time the business was migrating from a legacy system to our new CRM solution. They were able to not only significantly improve our web development architecture but our development and deployment processes as well as the functionality and performance of our portals. The feedback from customers has been overwhelmingly positive. Trailhead has proven themselves to be a valuable partner.

– BOB DOERKSEN, Vice President of Technology Services
at Montage Furniture Services

Technologies Used

When you hit the trails, it is essential to bring appropriate gear. The same holds true for your digital technology needs. That’s why Trailhead builds custom solutions on trusted platforms like .NET, Angular, React, and Xamarin.

Expertise

We partner with businesses who need intuitive custom software, responsive mobile applications, and advanced cloud technologies. And our extensive experience in the tech field allows us to help you map out the right path for all your digital technology needs.

  • Project Management
  • Architecture
  • Web App Development
  • Cloud Development
  • DevOps
  • Process Improvements
  • Legacy System Integration
  • UI Design
  • Manual QA
  • Back end/API/Database development

We partner with businesses who need intuitive custom software, responsive mobile applications, and advanced cloud technologies. And our extensive experience in the tech field allows us to help you map out the right path for all your digital technology needs.

Our Gear Is Packed and We're Excited to Explore with You

Ready to come with us? 

Together, we can map your company’s tech journey and start down the trails. If you’re set to take the first step, simply fill out the contact form. We’ll be in touch – and you’ll have a partner who cares about you and your company. 

We can’t wait to hear from you! 

Thank you for reaching out.

You’ll be getting an email from our team shortly. If you need immediate assistance, please call (616) 371-1037.