簡體   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