繁体   English   中英

使用MonoTouch创建自定义图像滤镜

[英]Creating a custom image filter using MonoTouch

我正在使用Xamarin for iOS即时创建合成图像。 我有两张图像,一幅是基本图像(黑白),另一幅是用于滤色镜的alpha蒙版“贴图”。 然后,在运行时提供RGB值,这样我就可以使合成图像成为应具有的颜色。

我已经找到了很多用于更改整个图像的解决方案,但是我很难找到一个很好的解决方案来创建仅对蒙版贴图中包含的区域(带有alpha值)进行着色的滤色器:

基本图片:

在此处输入图片说明在此处输入图片说明

产生的图像(如果我告诉我要红色):

在此处输入图片说明

在MonoDroid中,我能够创建一个自定义ImageView并重写OnDraw方法,然后使用ColorMatrixColorFilter,其工作方式像一个超级按钮,但不知道如何在MonoTouch中完成相同的任务。

这是我为MonoDroid做的事情:

    protected override void OnDraw(Canvas canvas)
    {
        if (_alphaMask == null)
            _alphaMask = BitmapFactory.DecodeResource(Resources, GetDrawable("star_mask"));

        if(_image == null)
            _image = BitmapFactory.DecodeResource(Resources, GetDrawable("star"));

        AdjustColor(_color, canvas, _alphaMask, _image);
    }

    private static void AdjustColor(Color color, Canvas c, Bitmap alphaMask, Bitmap image)
    {
        float R = color.R;
        float G = color.G;
        float B = color.B;
        var maskPaint = new Paint();
        var mat = new[]
        {
            0, 0, 0, 0, R, //red
            0, 0, 0, 0, G, //green
            0, 0, 0, 0, B, //blue
            0, 0, 0, 1, 0  //alpha
        };
        ColorMatrix cm = new ColorMatrix(mat);
        maskPaint.SetColorFilter(new ColorMatrixColorFilter(cm));
        c.DrawBitmap(image, 0, 0, null);
        c.DrawBitmap(alphaMask, 0, 0, maskPaint);
    }

好的...不是最优雅的解决方案,但是我在彼此之上创建了两个ImageView

在基础图像之上是MaskView然后使用以下方法创建彩色的UIImage

private UIImage GetColoredImage(string imageName, Color color)
    {
        UIImage image = UIImage.FromBundle(imageName);

        UIGraphics.BeginImageContext(image.Size);
        CGContext context = UIGraphics.GetCurrentContext();

        context.TranslateCTM(0, image.Size.Height);
        context.ScaleCTM(1.0f, -1.0f);

        var rect = new RectangleF(0, 0, image.Size.Width, image.Size.Height);

        // draw image, (to get transparancy mask)
        context.SetBlendMode(CGBlendMode.Normal);
        context.DrawImage(rect, image.CGImage);

        // draw the color using the sourcein blend mode so its only draw on the non-transparent pixels
        context.SetBlendMode(CGBlendMode.SourceIn);
        context.SetFillColor(color.R / 255f, color.G / 255f, color.B / 255f, 1);
        context.FillRect(rect);

        UIImage coloredImage = UIGraphics.GetImageFromCurrentImageContext();
        UIGraphics.EndImageContext();
        return coloredImage;
    }

如果有人有更好的解决方案(也许使用CIFilter ),我很乐意看到它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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