简体   繁体   中英

Correct way to shorten code with many casts and obvious patterns in C#

So, I have an app that is doing some painting on screen. I'm operating with doubles, but to paint, I have to use floats or ints. So, stuff like this happens frequently:

g.DrawEllipse(monsterPen, new Rectangle(
  (int)Math.Round(x - (double)sizeVessel * 9.0 / 20.0), 
  (int)Math.Round(y - (double)sizeVessel * 9.0 / 20.0), 
  (int)Math.Round(sizeVessel * 18.0 / 20.0),
  (int)Math.Round(sizeVessel * 18.0 / 20.0)));

While it could look like this

g.DrawEllipse(monsterPen, NewRectangleFromD(
  x - (double)sizeVessel * 9.0 / 20.0),
  y - (double)sizeVessel * 9.0 / 20.0),
  sizeVessel * 18.0 / 20.0,
  sizeVessel * 18.0 / 20.0)));

Or even like this

DrawCircle(g, monsterPen, x, y, sizeVessel * 9.0 / 20.0)

However, I'm not sure how to better do it.

In C/C++, if my memory serves me well, you could make an alias, saying that, for example this code:

DrawCircle(g, p, x, y, r) 

should be for all purposes treated as:

g.DrawEllipse(p, new Rectangle(
  (int)Math.Round(x - r / 2.0), 
  (int)Math.Round(y - r / 2.0), 
  (int)Math.Round(r), 
  (int)Math.Round(r))

But I can't find such option in C#. With no ability to force inline (I'm working in .Net 4.0) I am affraid that If I just declare a DrawCircle method that does that, I'll slow down my application (those draw calls are done quite often).

So, what is the correctt approach to take here?

One option is to use extention methods :

public static class GraphicsExtentions
{
    public static void DrawEllipse(this Graphics g, Pen pen, double x, double y, double width, double height)
    {
        g.DrawEllipse(pen, (int)x, (int)y, (int)width, (int)height);
    }
}

Which you call like this:

double x, y, w, h;
...
g.DrawEllipse(pen, x, y, w, h);

And if you want it to be super fast, you could look at the aggressive inlining attribute :

[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void DrawEllipse(this Graphics g, Pen pen, double x, double y, double width, double height)
{
    g.DrawEllipse(pen, (int)x, (int)y, (int)width, (int)height);
}

I'll answer here to point out why you shouldn't bother about that.

You're using GDI+, which is a software renderer. Doing intensive graphics with this library will be painfully slow anyway.

How many CPU cycles are needed to call a function? And how many are needed to actually draw an ellpise in software? I don't have the figures, but I'm sure of one thing: they'll be several orders of magnitude apart.

Conclusion: You're trying to optimize the wrong thing here. If you want to display graphics fast , use a hardware accelerated solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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