如何在ios xamarin c#中获得正确的触摸像素值

本文关键字:触摸 像素 ios xamarin | 更新日期: 2023-09-27 17:58:30

你好,我正在Xamarin C#中尝试获取触摸像素的颜色,但我有时会得到错误的值,R=255,G=0,B=0,A=0我的代码出了什么问题?

 private UIColor ColorOfPoint(CGPoint point)
    {
        byte[] pixel = {0,0,0,0};
        using(CGColorSpace oColorSpace = CGColorSpace.CreateDeviceRGB())
        using(CGBitmapContext oContext = new CGBitmapContext(pixel,
                                                     1, 1, 8, 4, oColorSpace, CGBitmapFlags.PremultipliedLast & CGBitmapFlags.AlphaInfoMask))
        {
            oContext.TranslateCTM(-point.X,-point.Y);
            img.Layer.RenderInContext(oContext);
            oContext.Dispose();
            oColorSpace.Dispose();
        }
        UIColor color = new UIColor(pixel[0]/255,pixel[1]/255,pixel[2]/255,pixel[3]/255);
        return color;
    }

如何在ios xamarin c#中获得正确的触摸像素值

使用UIColor.FromRGBA而不是new UIColor(....)

我就是这样做的:

byte[] alphaPixel = { 0, 0, 0, 0 };
protected UIColor GetColorAtTouchPoint(CGPoint point)
{
    var colorSpace = CGColorSpace.CreateDeviceRGB();
    var bitmapContext = new CGBitmapContext(alphaPixel, 1, 1, 8, 4, colorSpace, CGBitmapFlags.PremultipliedLast);
    bitmapContext.TranslateCTM(-point.X, -point.Y);
    view.Layer.RenderInContext(bitmapContext);
    return UIColor.FromRGBA(alphaPixel[0], alphaPixel[1], alphaPixel[2], alphaPixel[3]);
}