UWP Маскировка изображения с использованием другого изображения в качестве маски - PullRequest
0 голосов
/ 17 мая 2018

Кто-нибудь знает какие-либо способы использования изображения в качестве маски для другого изображения в UWP, единственная маскирующая функция, которую я вижу, - это CompositionMaskBrush, которая, я не верю, может достичь того, чего я хочу. Примером того, чего я хочу достичь, является следующее. У меня есть сплошной черный PNG в форме чехла для мобильного телефона, пользователь добавляет свое собственное изображение, которое затем обрезается и маскируется к размерам сплошного черного PNG - в результате на изображении ниже.

Любая помощь будет принята с благодарностью. Я потратил довольно много времени на поиски решения.

Пример изображения здесь

1 Ответ

0 голосов
/ 12 июня 2018

Просто отправляю сообщения всем, кому нужно, и отвечаю на это, но мне наконец-то удалось найти решение с использованием Win2D и Imageloader.

Вот ссылка на ImageLoader.Обратите внимание, что мне пришлось откатить несколько версий, чтобы все работало так, как указано в документации.Ссылка ниже на версию, которую я использую.Все, что позже этой версии, не будет работать с примером кода, который я собираюсь опубликовать.https://www.nuget.org/packages/Robmikh.Util.CompositionImageLoader/0.4.0-alpha

    private Compositor _compositor;
    private IImageLoader _imageLoader;
    private CompositionEffectFactory _effectFactory;

    private async void InitMask()
    {


        // Store our Compositor and create our ImageLoader.
        _compositor = ElementCompositionPreview.GetElementVisual(this).Compositor;
        _imageLoader = ImageLoaderFactory.CreateImageLoader(_compositor);

        // Setup our effect definition. First is the CompositeEffect that will take
        // our sources and produce the intersection of the images (because we selected
        // the DestinationIn mode for the effect). Next we take our CompositeEffect 
        // and make it the source of our next effect, the InvertEffect. This will take 
        // the intersection image and invert the colors. Finally we take that combined 
        // effect and put it through a HueRotationEffect, were we can adjust the colors
        // using the Angle property (which we will animate below). 
        IGraphicsEffect graphicsEffect = new HueRotationEffect
        {
            Name = "hueEffect",
            Angle = 0.0f,
            Source = new InvertEffect
            {
                Source = new CompositeEffect
                {
                    Mode = CanvasComposite.DestinationIn,
                    Sources =
                    {
                        new CompositionEffectSourceParameter("image"),
                        new CompositionEffectSourceParameter("mask")
                    }
                }
            }
        };
        // Create our effect factory using the effect definition and mark the Angle
        // property as adjustable/animatable.
        _effectFactory = _compositor.CreateEffectFactory(graphicsEffect, new string[] { "hueEffect.Angle" });

        // Create MangedSurfaces for both our base image and the mask we'll be using. 
        // The mask is a transparent image with a white circle in the middle. This is 
        // important since the CompositeEffect will use just the circle for the 
        // intersectionsince the rest is transparent.

        var managedImageSurface = await _imageLoader.CreateManagedSurfaceFromUriAsync(new Uri("http://sendus.pics/uploads/" + ImagePass + "/0.png", UriKind.Absolute));
        //var managedImageSurface = await _imageLoader.CreateManagedSurfaceFromUriAsync(new Uri("ms-appx:///Assets/colour.jpg", UriKind.Absolute));
        var managedMaskSurface = await _imageLoader.CreateManagedSurfaceFromUriAsync(new Uri("ms-appx:///" + MaskImage, UriKind.Absolute));

        // Create brushes from our surfaces.
        var imageBrush = _compositor.CreateSurfaceBrush(managedImageSurface.Surface);
        var maskBrush = _compositor.CreateSurfaceBrush(managedMaskSurface.Surface);

        // Create an setup our effect brush.Assign both the base image and mask image
        // brushes as source parameters in the effect (with the same names we used in
        // the effect definition). If we wanted, we could create many effect brushes
        // and use different images in all of them.
        var effectBrush = _effectFactory.CreateBrush();
        effectBrush.SetSourceParameter("image", imageBrush);
        effectBrush.SetSourceParameter("mask", maskBrush);

        // All that's left is to create a visual, assign the effect brush to the Brush
        // property, and attach it into the tree...
        var visual = _compositor.CreateSpriteVisual();

        visual.Size = new Vector2(MaskH, MaskW);
        visual.Offset = new Vector3(0, 300, 0);

        visual.Brush = effectBrush;

        ElementCompositionPreview.SetElementChildVisual(this, visual);
    }
...