0

I have been using the code from here to add some text to my UIImage, however the quality on the image gets really bad. I have narrowed down the code a lot, to this:

    public UIImage EditImage(UIImage myImage)
    {
        using (CGBitmapContext ctx = new CGBitmapContext(IntPtr.Zero, 75, 75, 8, 4 * 75, CGColorSpace.CreateDeviceRGB(), CGImageAlphaInfo.PremultipliedFirst))
        {
            ctx.DrawImage(new CGRect(0, 0, 75, 75), myImage.CGImage);
            return UIImage.FromImage(ctx.ToImage());
        }
    }

MyImage is a PNG image. I have added them like this:

  • MyImage.png (100x100 pixels)
  • MyImage@2.png (150x150 pixels)
  • MyImage@3.png (200x200 pixels)

I am not really sure which one of them is used, but when I inspect the image at runtime, the sizes are 75x75 nint (native int). That's why I set the CGBitmapContext height and width to 75.

My problem is that after processing myImage through this function the quality gets very poor. If I skip this process and just use myImage the quality is excellent, however I need the CGBitmapContext to add some text to the image.

Does anyone have any idea what is causing it to be bad quality, and how I can fix it? For the record, I am testing on an iPhone 6S.

mathkid91
  • 659
  • 2
  • 10
  • 27

1 Answers1

0

You have multiple misunderstandings.

Lets start with the image sizes. If your base image is 100x100 the @2x version should be 200x200 because it is double the resolution. Following this schema your @3x should be 300x300. The operating-system will choose the right one depending on the capabilities of your device. With a 6S it should be @2x depending on how you load the image.

Lets move on to the way you are creating the CGBitmapContext. The source of your code contains exactly what you need but you changed it to fix values and now wonder why your image is 75x75. The bad quality comes right from that, because the system is now resizing your original image.

tequila slammer
  • 2,821
  • 1
  • 18
  • 25
  • Thanks for answer. I see I may have made a mistake in the image size, but is this relevant for my case? Is my app reading my 100x100 image, and thus is expecting a 200x200 image, or will my @2x image just look smaller on screen than when the device is using original (@1x)? Also, as long as I am resizing down, the quality should not be as bad as it is in my code. I have found a workaround that I have forgotten to post, and the images are significantly better now, even with a resize. – mathkid91 Jun 25 '17 at 20:29