BadCats
@BadCats

Изменение прозрачности image с помощью binding?

В Xamarin приложении имеется следующая структура страницы: (к центру по содержанию) Frame - StackLayout - ScrollView -Grid с двумя строками и одним столбцом - и в первой строке элемент Image, а во второй метка - lable. Вот собственно код:
InitializeComponent();
        Label lb = new Label { Text="pasta"};
      img = new Image {Source ="pasta.jpg" };
        Frame fr = new Frame { HeightRequest=250, WidthRequest=250  };
        StackLayout st = new StackLayout {HeightRequest=fr.HeightRequest , WidthRequest =fr.WidthRequest , Orientation=StackOrientation.Vertical };
        sc  = new ScrollView { WidthRequest=st.WidthRequest , HeightRequest = st.HeightRequest  };
        Grid gr = new Grid {
            RowDefinitions = { new RowDefinition { Height =new GridLength(sc.HeightRequest) }, new RowDefinition { Height = new GridLength(sc.HeightRequest) } } ,
            ColumnDefinitions = { new ColumnDefinition { Width = new GridLength(sc.WidthRequest)} }

        };

        gr.Children.Add(img,0,0);
        gr.Children.Add(lb, 0, 1);
        sc.Content = gr;

        sc.Scrolled += On_scroll;
        st.Children.Add(sc);

        fr.Content = st;
        this.Content = fr;

Теперь, что собственно требуется: необходимо, что бы при скролинге прозрачность изображения уменшалась. Для этого я обращаюсь к событию Scrolled
sc.Scrolled += On_scroll;
 stp = new Stepper { Increment=0.5};
  img.BindingContext = Img_Pr;//привязываем Img_Pr к   img.BindingContext
private void On_scroll(object sender, ScrolledEventArgs e)
    {
        stp.ValueChanged += Scroll_Step_img; //вызываем обработку stepper
    }

что бы контролировать степень прозрачности - я использую Stepper - обработчик которого я и вызываю в обработчике события Scrolled. На объекта Stepper - stp - я вызываю событие ValueChanged и подписываю на него обработчик.

Для того что бы контролировать прозрачность изображения -т.к у него нет такого свойства, я решил создать BindableProperty
public  class Image_Property_Class : Xamarin.Forms.Image
{
    public static readonly BindableProperty transperentProperty = BindableProperty.Create("Transparent", typeof(Color), typeof(Xamarin.Forms.Image), new Color(255, 255, 255, 0));

    public Color Transparent
        {
        set { SetValue(transperentProperty,value); }

        get { return (Color)GetValue(transperentProperty); }
        }
  }

-для этого я создал класс исследующийся от класса Image и уже в нем создал BindableProperty. По идее через него я хочу менять значение альфа канала исходного изображения - делая его прозрачнее.
public static Image_Property_Class Img_Pr = new Image_Property_Class { };//объект привязки

В обработчике события ValueChanged объекта stp
public static void Scroll_Step_img(object sender, ValueChangedEventArgs e)
    {
        //настраиваем объект привязки
        Img_Pr.SetBinding(Image_Property_Class.transperentProperty, "img.BackgroundColor");
        //устанавливаем новое значение
        Img_Pr.Transparent = new Color(img.BackgroundColor.R, img.BackgroundColor.G, img.BackgroundColor.B, e.NewValue);
    }

я настраиваю привязку устанавливая зависимость и передавая собственно самому свойству Transperent - новое значение в виде аргумента события -e. Но при этом при скролинге изображение не становится прозрачнее. Вот еще раз полный код по-порядку:
ScrollView sc;
   public static Image img;
    Stepper stp;
    public MainPage()
    {
        InitializeComponent();
        Label lb = new Label { Text="pasta"};
      img = new Image {Source ="pasta.jpg" };
        Frame fr = new Frame { HeightRequest=250, WidthRequest=250  };
        StackLayout st = new StackLayout {HeightRequest=fr.HeightRequest , WidthRequest =fr.WidthRequest , Orientation=StackOrientation.Vertical };
        sc  = new ScrollView { WidthRequest=st.WidthRequest , HeightRequest = st.HeightRequest  };
        Grid gr = new Grid {
            RowDefinitions = { new RowDefinition { Height =new GridLength(sc.HeightRequest) }, new RowDefinition { Height = new GridLength(sc.HeightRequest) } } ,
            ColumnDefinitions = { new ColumnDefinition { Width = new GridLength(sc.WidthRequest)} }

        };

        gr.Children.Add(img,0,0);
        gr.Children.Add(lb, 0, 1);
        sc.Content = gr;

        sc.Scrolled += On_scroll;
        st.Children.Add(sc);

        fr.Content = st;
        this.Content = fr;
       stp = new Stepper { Increment=0.5};
        img.BindingContext = Img_Pr;//привязываем Img_Pr к   img.BindingContext



    }
    public static Image_Property_Class Img_Pr = new Image_Property_Class { };//объект привязки


    private void On_scroll(object sender, ScrolledEventArgs e)
    {
        stp.ValueChanged += Scroll_Step_img; //вызываем обработку stepper
    }

    public static void Scroll_Step_img(object sender, ValueChangedEventArgs e)
    {
        //настраиваем объект привязки
        Img_Pr.SetBinding(Image_Property_Class.transperentProperty, "img.BackgroundColor");
        //устанавливаем новое значение
        Img_Pr.Transparent = new Color(img.BackgroundColor.R, img.BackgroundColor.G, img.BackgroundColor.B, e.NewValue);
    }

}

BindablePeoperty
public  class Image_Property_Class : Xamarin.Forms.Image
{
    public static readonly BindableProperty transperentProperty = BindableProperty.Create("Transparent", typeof(Color), typeof(Xamarin.Forms.Image), new Color(255, 255, 255, 0));

    public Color Transparent
        {
        set { SetValue(transperentProperty,value); }

        get { return (Color)GetValue(transperentProperty); }
        }
}
  • Вопрос задан
  • 77 просмотров
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы