App Rating for Windows Phone 7 Source Code Released

Mar 31, 2011

I’m releasing the App Rating app source code today, under MS-RL license (http://www.opensource.org/licenses/ms-rl). In summary, you can use the App Rating's source for commercial (even directly competitive) projects and are required to provide updates to the source code back to me and the community.

The nice part that you can get from AppRating’s code is the WebApi.cs class, which is optimized for network REST requests, dynamically changing priority of requests, cancelling, etc, and is very lightweight.

Download source code here: http://nokola.com/sources/apprating.zip

I’m still figuring out the correct license for the rest of my sources. Until then they are all under NNCL (http://nokola.com/nncl). btw I’m very open to giving it out to people, per the terms of the license. Already approved few requests.

Hope you like it! Please comment!

  

New Fantasia Painter, Windows Phone 7 Source Code Pack 1, New License

Mar 25, 2011

I’m back from the fields of Fantasia's [software development]!

This post contains:

  1. New Fantasia Painter available, with 20 effects, an "alive" Fairy Lights brush, Text, symbols and photo functionality
  2. Source code for Fantasia’s high-usability controls tuned for WP7: color pickers, improved slider and easing progress bar.
  3. My new license (NNCL), which promotes fair commercial and personal use while protecting IP and ensures giving back to the community

New Fantasia Painter

The new app has just been released to the marketplace. There’s a free, ad-sponsored version too! People are thrilled by the updates!

Get Fantasia Painter

wp7_152x50_blue 

Get Fantasia Painter Free (Ad Sponsored)

wp7_152x50_blue

Here are the new intro videos and short description of new effects – and I’m just scratching the surface:

Mold tool to change body shape, smiles, enlarge eyes, etc (similar to Liquify in Photoshop), 20 effects, Text, 500+ symbols, speech bubbles.

Higher quality effects and brushes – see “Makeup, Eye color and Eye Shape in 60 seconds” below 

Two and a half minute overview of many effects, new “alive” Fairy Lights brush. Complex (and unique) photo effects that do amazing job, like Color Balance to fix tints due to poor lighting (it’s smarter than the typical balance algorithms), Lifelike Colors.

The power of Fantasia Painter’s effects is that they can all be selectively applied to part of an image. Fantasia also combines effect by usage: for example, instead of having 3 separate effects for Brightness/Contrast, Saturation and Exposure, you have one – this can save you a lot of time when editing pictures.

The 4 image enhancements (Color balance, Lifelike Colors, Bright/Contr/Sat/Expo, White Point/Rebalance) effects are roughly equivalent to 7 or 8 effects from other photo editing tools, plus multiple Photoshop enhancement steps (in the case of Lifelike Colors).

Here are some things I’ve done with Fantasia on an actual device in the last day or so:

Painted from scratch in < 2 minutes, starting with Rainbow background and using Makeup brushes and Recolor effect:

cool

Auto Color balance reveals hidden parts of this sky picture!

Original (left), Auto Balance (Right)

1331500_41770898auto balance

 

Gentle Painter effect:

gentle (2)

Source Code – Windows Phone Controls Pack 1

The source code is licensed under NNCL (see below). It means that you must get permission from me in order to use it in any project (commercial, even when released for free).

I will likely allow it, but will require you to contribute code (or article, or something else) to either me or the community in return. In case you’re direct competitor, I will most likely flat out refuse, or ask you to either trade me some of your source code or release it publicly.

I spent 2 months doing usability testing of the controls, and they are highly usable for all my tested age groups (4 to 70), by people with different levels of computer knowledge and different finger width. They are also very UI-friendly (just put them in StackPanel with Margin 0 and you’re good), lightweight, and fast.

Download Nokola Windows Phone Source Pack 1

The pack includes:

imageimageimageimage

What’s so good about the color pickers above? It’s the fact that most colors can be selected with single finger. This is a significant usability improvement. I found out that the “typical” color picker (like the one on http://fantasia.nokola.com) is very hard for phone users to choose color from. Especially for non-developers. In most cases, they would drag their finger on the hue selector on the right, and wonder “why didn’t the color change?” (it didn’t, because the left rect was set to white, for example). The color picker above resolves the issue since a combination of hue/saturation/value is presented in 2D, while the side rectangle allows to further customize color to be able to choose from the full color range. This allows for single-finger selection from most used colors.

The “better slider”, has the following features:

  • significantly easier to choose value (try it on an actual device)
  • larger hit test area
  • shows slider value
  • carefully engineered so you can easily select minimum and maximum value too

It also has a drawback – it is not very usable with scrolling UI. But for non-scrolling UI it’s the bomb Smile

Easing progress bar: after much experimentation, I found out that when a particular easing function is applied to a progress bar, it appears that the progress takes less time. Try the two progress bars in the demo one after the other and see for yourself Smile

Nokola-NCL (Nokola Non-Competitive License or NNCL)

Last but not least all of my source code is now licensed under NNCL (http://nokola.com/nncl), which stands for “Nokola Non-Competitive License.” (I expect other people to come up with similar <your name>-NCL licenses btw).

I was wondering: how do I share my source code, and allow non-competitive programs to use it, while protecting myself from competitors? How do I make sure that when the code I release is improved, others can benefit from it too (including commercial use)?

The MS-PL license does not protect me from competitors, and it also does not ensure that improvements are returned back to the community. For example, one could pick up my Silverlight slider control, which used to be licensed under MS-PL, redo it for Windows Phone 7, and use it privately.

The GPL does not allow commercial use with competitor protection.

The reason while I was “in the dark” for few months, not releasing any code was due to the above dilemmas.

Thus the need of NNCL Smile

NNCL License Summary
The NNCL License has the following goals:

  • improve source code sharing and availability to community. Many people, including MVPs just don’t release any of their source code in fear that it might be (and in fact, it will be) used by direct competitors. In mind mind, the choices are: 1. release the source under MS-PL, which means anyone can use and (morally) abuse it. 2. don’t release it at all (which is what a lot of people do today – just check how much high-quality and novel Silverlight vs Windows Phone 7 code articles are being released) 3. Release it under commercial, but reciprocal license line NNCL.
  • ensure direct and indirect competitors only use code and assets if they provide something back to the software community of the original code author

You have to contact me (Nokola: nikola.mihaylov@gmail.com) for permission before using source or images on Windows Phone 7 or other mobile device.
I am very likely to allow you to use it, with certain requirements, depending on the situation. For example, I might ask you to release specific source publicly to the community.
Sometimes I might just flat out refuse (if you're a direct competitor), unless you have something to offer me or the community in return.

Any changes you make to improve the controls, must be made available to me (and likely to the community) for commercial use, licensed under NNCL.
All derivative works have to be licensed under NNCL as well. You can include a <your name here>-NCL license if you create derivative works too.

Read the full license text here: http://nokola.com/nncl

And I hope the NNCL is fair – what do you think?

Hope you like the updates! Please comment!

Remember to search for Fantasia Painter on the marketplace, get it, use it, tweet it, rate it, and comment here if you see issues.

    

App Ratings Updated with search and 6-10x times faster

Dec 22, 2010

I updated App Rating to have search for apps, show rating since last update, and be much faster. Unlike other similar rating apps on the marketplace, App Rating shows a single-screen per-market score so you can compare your app in different markets easily. To use, search the marketplace for “App Rating” or click here to get the app

wp7_152x50_blue

Video of the new functionality:

Unless I get strong feedback for new features, I’m not planning to invest more in App Ratings. It’s good enough for me Smile

  

Games for Windows Phone 7 Resources: Reducing Load Times, RPG Kit; Other

Dec 11, 2010

Microsoft released the new games education pack including a multi-platform tutorial, RPG starter kit ported to Windows Phone 7.

I really like the comparisons of the isostore reads in MB/sec in the “reducing load times paper”, and the game samples that’s why blogging it.

Here’s the pack:

http://create.msdn.com/en-US/home/news/new_education_dec_2010

 

Kind of off topic: I got few asks “how do you make the mouse cursor in your videos?”

I created my own mouse cursor (just a circle .PNG, then convert to .cur) and I set the OS system default cursor to it. You can download the cursor here: http://nokola.com/sources/circle.cur

I use Windows Movie Maker for the video editing – does someone have better (free/cheap) suggestions? What do you use?

    

2 New Apps - See Ratings Across Marketplaces and Prevent Phone Locking when Debugging In Visual Studio

Dec 10, 2010

Did you know that by default you see only ratings for your marketplace? I didn’t, and was very amazed to find out my apps have more reviews and ratings than what shows up in my phone marketplace or Zune window.

Using App Ratings, you can now view the ratings by market on a single screen and access reviews in all markets. Search the marketplace for “App Ratings” or click here to get the app

wp7_152x50_blue

See how fast I can type on that keyboard: Smile

App Ratings uses Atom feed provided by Zune. For more info see the forum posts below:

http://forums.create.msdn.com/forums/p/64382/395208.aspx

http://forums.create.msdn.com/forums/p/66495/406864.aspx

The other app I’d like to mention is called “dev screen saver” and is made by a colleague and friend of mine. It can help prevent your phone from locking – great to use during long hour sessions of debug and deploy in Visual Studio to avoid having to manually unlock your phone. It also moves an image on screen to prevent burnout/burn-in effects and increase screen life.

I hope these apps will be usable to some people. Smile Bye bye Smile

  

Fantasia Painter Released for Windows Phone 7 + Tips

Dec 5, 2010

Edit Dec 8, 2010: Updated tips (I was too excited the first release and missed some important info in the “how to speed load/save state tip #3)

Yes! See the 1-minute intro HD video of the drawing app below. In this version, you can add makeup to someone’s face, change eye color (or other colors). It also comes with all-new fur smudge, and color reveal/hide brushes as well as rainbow mode for all existing Fantasia brushes. Pinch to zoom and move with 2 fingers.

Click here to try or buy Fantasia Painter for your Windows Phone 7

Here is a little longer (2 minutes) video that shows some of the Fantasia Painter’s drawing capabilities in action:

Note: I forgot to mention that you can pinch to Zoom to paint small details (this allows you to draw the small details on the birdie on an actual device, not just the emulator).

Click here to buy Fantasia Painter for your Windows Phone 7 (trial mode supported as well)

Please feel free to send link to this blog to everyone, try, buy, and/or play with the app! I appreciate it!

 

Technical Details and Tips

The phone version also supports “painting with effect” like the desktop version. For now I have a couple of simple effects that are only exposed through brushes (such as Saturation and Tint). I also added blending modes, which allow for “lighter” and “darker” makeup. The new brushes/effects share the same code (I add reference to the same DLL) as the web Silverlight version of Fantasia and go through the same effect pipeline, which is great! Smile

While developing Fantasia for Windows Phone 7, I noticed collected some useful tips for developers that will hopefully make your life easier. There were some nasty crashes that were hard to find.

Tip 1: Preventing crash/hangup when using TouchPanel and Touch classes

I’m using TouchPanel and Touch for the pinch-to-zoom and move with 2 fingers capabilities. Can you tell what’s wrong with this code:

public partial class MainPage : PhoneApplicationPage
{
    // Constructor

    public MainPage()
    {
        InitializeComponent();

        Touch.FrameReported += Touch_FrameReported;

If you do something like what I did above, you’ll face a very weird issue – when navigating using NavitationService.Navigate() instead of using the back button on the phone, you’ll get a seemingly-random exception for a missing element. What’s going on?

In Windows Phone 7 your page can be created/destroyed whenever it’s not visible (read about Tombstoning). What is interesting though is that if you use NavigationService.Navigate(), your page may be re-created if it was not visible for long time even if your application is still running. The old page should get garbage collected – right? Actually it’s not, since you have the static Touch class referencing a function from your page. Thus, whenever the user taps on the phone, you’ll get a function call in a page that is invalid.

To fix the above issue, override OnNavigatedTo and OnNavigatedFrom and Touch.FrameReported += Touch_FrameReported; and Touch.FrameReported -= Touch_FrameReported; This way your page will get recycled correctly

Tip 2: Use Windows Snippping Tool to get perfect 480x800 screenshots of the Windows Phone 7 emulator.

This really saved me a lot of time. In the Windows start menu search, type “snip” and open the snipping tool. Open the “New” menu and select “Window Snip”. Click on the emulator window (the emulator zoom should be at 100%). You’re done!

Tip 3: Faster state load/save using isolated storage

I noticed an interesting issue: the first time I deployed Fantasia on a real device, loading the state using IsolatedStorageSettings (8 int variables and the picture bitmap), took about 8 seconds! Way too long Smile

Using IsolatedStorageFile to do the same thing takes <0.2 sec on my Samsung Focus.

IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication();
IsolatedStorageFileStream file = storage.OpenFile(“myfile.dat”, System.IO.FileMode.Open);
byte[] data = new byte[file.Length];
file.Read(data, 0, data.Length);
file.Close();

Tip 4: WriteableBitmap render speed

WriteableBitmap.Render() was considerably slow on the device compared to PC, to the point where a single stroke would have 0.5 seconds lag for several lines. Thus I had to completely redo the Silverlight line rendering in code, which managed to speed up the whole drawing quite a bit (somewhere between 10 and 100 times). I also improved my brush rendering by avoiding redrawing pixels when they are already drawn and by using optimizations such as drawing one pixel with opacity X*10 instead of 10 pixel with opacity X (another huge speed improvement there.)

Invalidate(): Turns out, the performance here wasn’t too bad. It’s still wise to avoid Invalidate() I could achieve noticeably faster speed by reducing the number of Invalidate() calls per second.

Tip 5: Preventing the panorama and pivots from scrolling

I needed this functionality in order to have the color pickers work as expected and not scroll the view.

This post has sample code: http://blogs.msdn.com/b/luc/archive/2010/11/22/preventing-the-pivot-or-panorama-controls-from-scrolling.aspx

Unfortunately, the above code suffers a similar crashing issue like in Tip 1 above. It’s fairly easy to fix by ensuring the events are unhooked as appropriate. I will likely post the fixed version sometime soon (unless someone else does).

I did 1 month of usability testing (let’s hope it was worth it!) Will publish more info at a later date. There are some very interesting findings such as what is a good color picker, slider, etc.

That’s all for now! Please remember to try out Fantasia Painter, if you’d like it buy it, review, send it to friends, tweet it, facebook it, etc!

I appreciate it! Please send me comments here or in the reviews on the Phone!

    

Anti-aliased Lines And Optimizing Code for Windows Phone 7–First Look

Oct 14, 2010

Update Oct 27, 2010: Thanks to Shai Rubinshtein (see comments) for pointing out an issue with AALine(), source code updated below and in link.

Some (long) time ago I decided to port Fantasia Painter to Windows Phone 7. When I ran it on an actual device (my friend’s, no I don’t have it yet unfortunately) last week, updating the screen while painting had about 0.5 second lag. This lag is quite unacceptable for a painting app. Here’s how I fixed it.

Turns out, WriteableBitmap.Render() and Invalidate() incur some significant performance cost. I decided to replace the .Render(new Line()) with my own line-drawing function.

I ended up creating my own anti-aliased and alpha blending function, that has similar quality to Render(new Line()) and runs 4.8 times faster. Here’s a proof that it works Smile:

alphaSample1         alphaSample2

Contents of This Post

  • Line Drawing Algorithms
  • Optimizing for Windows Phone 7
  • The Actual Optimizations and Source Code

Line Drawing Algorithms

At first, I decided to use the basic aliased line that I had (now part of http://writeablebitmapex.codeplex.com/.) It turned out pretty ugly – the small spikes on the Furball brush became fat and aliased lines. At least it was running amazingly fast Smile

After a bit of research, I found out Wu’s and Gupta-Sproull’s anti-aliasing algorithms. Wu’s algorithm is fast, but the lines were too thin for my liking, the drawings didn’t look as “natural”.

You can look at a comparison pictures between the various algorithms here: http://igraphicsgroup.com/blog/2009/04/looking_at_different_types_of.html . On the comparison site: AGG (http://www.antigrain.com/demo/index.html) is an open source library that yields the best results in my opinion, but is slower and unfortunately licensed under GPL, which makes it unusable for me since I prefer to license my code under MS-PL which is OK for commercial use.

Here’s the speed comparison of the various algorithms, as tested on desktop PC. I have run only some of them on the device as well…will publish more results when I run all of them.

Note that I have not finished optimizing Wu’s line algorithm. Also, DrawLineAlphaBlendOnOpaque is just an aliased line with alpha blending.

image

 

I decided to optimize the Gupta-Sproull algorithm and see how that works. Here are some sites I looked at:

The algorithm I used is based on http://courses.engr.illinois.edu/ece390/archive/archive-f2000/mp/mp4/anti.html#algo, with some tweaks and fixes.

Optimizing for Windows Phone 7

If you go and look at the first wave of Windows 7 Phone phones here http://windowsphone7.com/ you’ll notice most all of them (at the time of this writing) feature Qualcomm Snapdragon chipset QSD8250 series. From this overview: http://www.pdadb.net/index.php?m=cpu&id=a8250&c=qualcomm_snapdragon_qsd8250, we can see that the processor is 32-bit with ARMv7 instruction set.

It’s a RISC processor with lots of registers. This tells us that we should try putting functions inline vs calling them – e.g. the AlphaBlendNormalOnPremultiplied() function below is a great candidate. We should also try to use int32’s mostly.

Here’s another overview of the Snapdragon chipset: http://www.arm.com/markets/mobile/qualcomm-snapdragon-chipset.php.

The Actual Optimizations and Source Code

You can pick up the current source containing all functions (not well documented since work in progress, except the header of AALine()) mentioned above here: http://nokola.com/sources/DrawingHelper.zip

Note on premultiplied values: I had to take special care when alpha blending with WriteableBitmap pixels, since those are alpha-premultiplied. When using the source, make sure you pass the correct values (premultiplied or not depending on function.).

List of optimizations to the Gupta-Sproull algorithm – code below:

  • Making sure that the distance is within the range 0..1, saving significant amount of multiplies in the alpha blending function AlphaBlendNormalOnPremultiplied()
  • Since the alpha changes often, I changed the alpha blend function to blend “normal” (non-premultiplied) values, instead of converting the values to pre-multiplied format before calling the function (this saves ~6 or so multiplications per pixel)
  • Changed distance to range 0..1023 and moved all floating point calculations outside the drawing loop. The distance computations in the loop are all fixed-point int arithmetic.
  • Multiplied alpha to the “inc” variables before the loop, so we don’t have to multiply it by the distance in the AlphaBlendNormalOnPremultiplied(). Effectively moving the alpha*distance before the loop and replacing the multiplication with additions in the loop.
  • Replacing all multiplications in the loop with additions, by having all distance increments be multiplied just before the loop
  • In the blend function: replacing the high-quality RGB blending with a little bit lower quality (no visible difference whatsoever – maybe pixels are off by one). Note that alpha blending is still using the high-quality computation (value * 0x8081) >> 23 is the same as value / 255. This is optimized to value >> 8 which is the same as value / 256 for RGB.
  • Updated blend function to use uint instead of int (tests on desktop showed 5% faster)
  • Replaced the (g >> 8) << 8 with g & 0xFFFFFF00 in the blending function.
  • Combined the computation of R and B values into one when blending. This saves a lot of computations per pixel!:
    image

Disclaimer: I still have to test this on the phone to ensure I didn’t bug with the compiler optimizations, even though it seems it will yield much better results

Update Oct 18, 2010: Yeah it works great on actual device!

  • Last but not least: unrolling (copy-pasting 3 times) the AlphaBlendNormalOnPremultiplied function in the loop. This is not shown below for simplicity (it is implemented here: http://nokola.com/sources/DrawingHelper.zip). It improves speed by 20%

Potential future optimizations: getting rid of the floating point arithmetic completely (takes 0.2% CPU time now so probably not a big deal); improving speed of alpha blending further (lookup tables?)

/// <summary>
/// Draws an antialiased line, using an optimized version of Gupta-Sproull algorithm
/// </summary>
/// <param name="pixels">Pixels from a WriteableBitmap to draw to (premultiplied alpha format)</param>
/// <param name="pixelWidth">Width of the bitmap</param>
/// <param name="pixelHeight">Height of the bitmap</param>
/// <param name="x0">Start X</param>
/// <param name="y0">Start Y</param>
/// <param name="x1">End X</param>
/// <param name="y1">End Y</param>
/// <param name="sa">Opacity of the line (0..255)</param>
/// <param name="srb">Non-premultiplied red and blue component in the format 0x00rr00bb</param>
/// <param name="sg">Green component (0..255)</param>
public static void AALine(int[] pixels, int pixelWidth, int pixelHeight, int x0, int y0, int x1, int y1, int sa, uint srb, uint sg)
{

    if ((x0 == x1) && (y0 == y1)) return; // edge case causing invDFloat to overflow, found by Shai Rubinshtein

    if (x0 < 1) x0 = 1;
    if (x0 > pixelWidth - 2) x0 = pixelWidth - 2;
    if (y0 < 1) y0 = 1;
    if (y0 > pixelHeight - 2) y0 = pixelHeight - 2;

    if (x1 < 1) x1 = 1;
    if (x1 > pixelWidth - 2) x1 = pixelWidth - 2;
    if (y1 < 1) y1 = 1;
    if (y1 > pixelHeight - 2) y1 = pixelHeight - 2;

    int addr = y0 * pixelWidth + x0;
    int dx = x1 - x0;
    int dy = y1 - y0;

    int du;
    int dv;
    int u;
    int v;
    int uincr;
    int vincr;
   
    // By switching to (u,v), we combine all eight octants
    int adx = dx, ady = dy;
    if (dx < 0) adx = -dx;
    if (dy < 0) ady = -dy;

    if (adx > ady)
    {
        du = adx;
        dv = ady;
        u = x1;
        v = y1;
        uincr = 1;
        vincr = pixelWidth;
        if (dx < 0) uincr = -uincr;
        if (dy < 0) vincr = -vincr;

    }
    else
    {
        du = ady;
        dv = adx;
        u = y1;
        v = x1;
        uincr = pixelWidth;
        vincr = 1;
        if (dy < 0) uincr = -uincr;
        if (dx < 0) vincr = -vincr;
    }

    int uend = u + du;
    int d = (dv << 1) - du;        // Initial value as in Bresenham's
    int incrS = dv << 1;    // Δd for straight increments
    int incrD = (dv - du) << 1;    // Δd for diagonal increments

    double invDFloat = 1.0 / (4.0 * Math.Sqrt(du * du + dv * dv));   // Precomputed inverse denominator
    double invD2duFloat = 0.75 - 2.0 * (du * invDFloat);   // Precomputed constant

    const int PRECISION_SHIFT = 10; // result distance should be from 0 to 1 << PRECISION_SHIFT, mapping to a range of 0..1
    const int PRECISION_MULTIPLIER = 1 << PRECISION_SHIFT;
    int invD = (int)(invDFloat * PRECISION_MULTIPLIER);
    int invD2du = (int)(invD2duFloat * PRECISION_MULTIPLIER * sa);
    int ZeroDot75 = (int)(0.75 * PRECISION_MULTIPLIER * sa);

    int invDMulAlpha = invD * sa;
    int duMulInvD = du * invDMulAlpha; // used to help optimize twovdu * invD
    int dMulInvD = d * invDMulAlpha; // used to help optimize twovdu * invD
    //int twovdu = 0;    // Numerator of distance; starts at 0
    int twovduMulInvD = 0; // since twovdu == 0
    int incrSMulInvD = incrS * invDMulAlpha;
    int incrDMulInvD = incrD * invDMulAlpha;

    do
    {
        AlphaBlendNormalOnPremultiplied(pixels, addr, (ZeroDot75 - twovduMulInvD) >> PRECISION_SHIFT, srb, sg);
        AlphaBlendNormalOnPremultiplied(pixels, addr + vincr, (invD2du + twovduMulInvD) >> PRECISION_SHIFT, srb, sg);
        AlphaBlendNormalOnPremultiplied(pixels, addr - vincr, (invD2du - twovduMulInvD) >> PRECISION_SHIFT, srb, sg);

        if (d < 0)
        {
            // choose straight (u direction)
            twovduMulInvD = dMulInvD + duMulInvD;
            d += incrS;
            dMulInvD += incrSMulInvD;
        }
        else
        {
            // choose diagonal (u+v direction)
            twovduMulInvD = dMulInvD - duMulInvD;
            d += incrD;
            dMulInvD += incrDMulInvD;
            v++;
            addr += vincr;
        }
        u++;
        addr += uincr;
    } while (u < uend);
}

/// <summary>
/// Blends a specific source color on top of a destination premultiplied color
/// </summary>
/// <param name="pixels">Array containing destination color</param>
/// <param name="index">Index of destination pixel</param>
/// <param name="sa">Source alpha (0..255)</param>
/// <param name="srb">Source non-premultiplied red and blue component in the format 0x00rr00bb</param>
/// <param name="sg">Source green component (0..255)</param>
private static void AlphaBlendNormalOnPremultiplied(int[] pixels, int index, int sa, uint srb, uint sg)
{
    uint destPixel = (uint)pixels[index];
    uint da, dg, drb;

    da = (destPixel >> 24);
    dg = ((destPixel >> 8) & 0xff);
    drb = destPixel & 0x00FF00FF;

    // blend with high-quality alpha and lower quality but faster 1-off RGBs
    pixels[index] = (int)(
       ((sa + ((da * (255 - sa) * 0x8081) >> 23)) << 24) | // aplha
       (((sg - dg) * sa + (dg << 8)) & 0xFFFFFF00) | // green
       (((((srb - drb) * sa) >> 8) + drb) & 0x00FF00FF) // red and blue
    );

    //dr = ((destPixel >> 16) & 0xff);
    //db = ((destPixel) & 0xff);

    //uint srb = (uint)((sr << 16) | sb);

   
    //pixels[index] = (int)(
    //   ((sa + ((da * (255 - sa) * 0x8081) >> 23)) << 24) | // alpha
    //   (((((sr - dr) * sa) >> 8) + dr) << 16) | // red
    //   ( ((sg - dg) * sa + (dg << 8)) & 0xFFFFFF00 ) | // green
    //   ( (((sb - db) * sa) >> 8) + db ) ); // blue
}

Hope you like it! Please comment!

  

nokola.com | Terms | Log in

Recent

About the author

Happy & enjoying life. Software enthusiast.
The opinions I express here and on nokola.com are mine and not my employeer's (Microsoft).
This is the official blog of nokola.com. You can find Silverlight samples, coding stuff, and hopefully other interesting things here.