简体   繁体   中英

UIImage bad quality in iOS Xamarin

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.

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.

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