Xamarin.Forms Imagebutton

Download Sample 샘플 다운로드

ImageButton은 이미지를 표시하고 애플리케이션이 특정 작업을 수행하도록 지시하는 탭 또는 클릭에 응답합니다.

보기는 ImageButtonButton 보기와 Image 보기를 결합하여 콘텐츠가 이미지인 단추를 만듭니다. 사용자가 손가락으로 누르 ImageButton 거나 마우스로 클릭하여 애플리케이션이 특정 작업을 수행하도록 지시합니다. 그러나 보기 ImageButtonButton 달리 보기에는 텍스트 및 텍스트 모양에 대한 개념이 없습니다.

참고 항목

뷰에서 Button 이미지를 Button표시할 수 있는 속성을 정의하는 Image 동안 이 속성은 텍스트 옆에 Button 작은 아이콘을 표시할 때 사용됩니다.

이 가이드의 코드 예제는 FormsGallery 샘플에서 가져옵니다.

이미지 원본 설정

ImageButtonSource 이미지 원본이 파일, URI, 리소스 또는 스트림인 상태에서 단추에 표시할 이미지로 설정해야 하는 속성을 정의합니다. 다른 원본에서 이미지를 로드하는 방법에 대한 자세한 내용은 다음의 Xamarin.Forms이미지를 참조하세요.

다음 예제에서는 XAML에서 인스턴스화하는 ImageButton 방법을 보여줍니다.

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="FormsGallery.XamlExamples.ImageButtonDemoPage"
             Title="ImageButton Demo">
    <StackLayout>
        <Label Text="ImageButton"
               FontSize="50"
               FontAttributes="Bold"
               HorizontalOptions="Center" />

       <ImageButton Source="XamarinLogo.png"
                    HorizontalOptions="Center"
                    VerticalOptions="CenterAndExpand" />
    </StackLayout>
</ContentPage>

속성은 Source 에 표시되는 이미지를 지정합니다 ImageButton. 이 예제에서는 각 플랫폼 프로젝트에서 로드되는 로컬 파일로 설정되므로 다음 스크린샷이 표시됩니다.

Basic ImageButton

기본적으로 ImageButton 직사각형이지만 속성을 사용하여 둥근 모서리를 CornerRadius 제공할 수 있습니다. 모양에 대한 ImageButton 자세한 내용은 ImageButton 모양을 참조 하세요.

참고 항목

애니메이션 GIF를 ImageButton 로드할 수 있지만 GIF의 첫 번째 프레임만 표시됩니다.

다음 예제에서는 이전 XAML 예제와 기능적으로 동일하지만 전적으로 C#으로 구성된 페이지를 만드는 방법을 보여줍니다.

public class ImageButtonDemoPage : ContentPage
{
    public ImageButtonDemoPage()
    {
        Label header = new Label
        {
            Text = "ImageButton",
            FontSize = 50,
            FontAttributes = FontAttributes.Bold,
            HorizontalOptions = LayoutOptions.Center
        };

        ImageButton imageButton = new ImageButton
        {
            Source = "XamarinLogo.png",
            HorizontalOptions = LayoutOptions.Center,
            VerticalOptions = LayoutOptions.CenterAndExpand
        };

        // Build the page.
        Title = "ImageButton Demo";
        Content = new StackLayout
        {
            Children = { header, imageButton }
        };
    }
}

ImageButton 클릭 처리

ImageButtonClicked 사용자가 손가락이나 마우스 포인터로 탭할 ImageButton 때 발생하는 이벤트를 정의합니다. 이 이벤트는 손가락 또는 마우스 단추가 표면에서 해제될 때 발생합니다 ImageButton. ImageButton 탭에 응답하려면 true 해당 IsEnabled 속성이 설정되어 있어야 합니다.

다음 예제에서는 XAML에서 인스턴스화 ImageButton 하고 해당 Clicked 이벤트를 처리하는 방법을 보여줍니다.

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="FormsGallery.XamlExamples.ImageButtonDemoPage"
             Title="ImageButton Demo">
    <StackLayout>
        <Label Text="ImageButton"
               FontSize="50"
               FontAttributes="Bold"
               HorizontalOptions="Center" />

       <ImageButton Source="XamarinLogo.png"
                    HorizontalOptions="Center"
                    VerticalOptions="CenterAndExpand"
                    Clicked="OnImageButtonClicked" />

        <Label x:Name="label"
               Text="0 ImageButton clicks"
               FontSize="Large"
               HorizontalOptions="Center"
               VerticalOptions="CenterAndExpand" />
    </StackLayout>
</ContentPage>

이벤트는 Clicked 코드 숨김 파일에 있는 명명 OnImageButtonClicked 된 이벤트 처리기로 설정됩니다.

public partial class ImageButtonDemoPage : ContentPage
{
    int clickTotal;

    public ImageButtonDemoPage()
    {
        InitializeComponent();
    }

    void OnImageButtonClicked(object sender, EventArgs e)
    {
        clickTotal += 1;
        label.Text = $"{clickTotal} ImageButton click{(clickTotal == 1 ? "" : "s")}";
    }
}

ImageButton을 탭하면 OnImageButtonClicked 메서드가 실행됩니다. 인수 senderImageButton 이 이벤트를 담당합니다. 이를 사용하여 개체에 ImageButton 액세스하거나 동일한 Clicked 이벤트를 공유하는 여러 ImageButton 개체를 구분할 수 있습니다.

이 특정 Clicked 처리기는 카운터를 증가시키고 카운터 값을 다음과 같이 Label표시합니다.

Basic ImageButton Click

다음 예제에서는 이전 XAML 예제와 기능적으로 동일하지만 전적으로 C#으로 구성된 페이지를 만드는 방법을 보여줍니다.

public class ImageButtonDemoPage : ContentPage
{
    Label label;
    int clickTotal = 0;

    public ImageButtonDemoPage()
    {
        Label header = new Label
        {
            Text = "ImageButton",
            FontSize = 50,
            FontAttributes = FontAttributes.Bold,
            HorizontalOptions = LayoutOptions.Center
        };

        ImageButton imageButton = new ImageButton
        {
            Source = "XamarinLogo.png",
            HorizontalOptions = LayoutOptions.Center,
            VerticalOptions = LayoutOptions.CenterAndExpand
        };
        imageButton.Clicked += OnImageButtonClicked;

        label = new Label
        {
            Text = "0 ImageButton clicks",
            FontSize = Device.GetNamedSize(NamedSize.Large, typeof(Label)),
            HorizontalOptions = LayoutOptions.Center,
            VerticalOptions = LayoutOptions.CenterAndExpand
        };

        // Build the page.
        Title = "ImageButton Demo";
        Content = new StackLayout
        {
            Children =
            {
                header,
                imageButton,
                label
            }
        };
    }

    void OnImageButtonClicked(object sender, EventArgs e)
    {
        clickTotal += 1;
        label.Text = $"{clickTotal} ImageButton click{(clickTotal == 1 ? "" : "s")}";
    }
}

ImageButton을 사용하지 않도록 설정

애플리케이션이 특정 클릭이 유효한 작업이 아닌 특정 ImageButton 상태에 있는 경우가 있습니다. 이러한 경우 ImageButton 해당 IsEnabled 속성을 false.로 설정하여 사용하지 않도록 설정해야 합니다.

명령 인터페이스 사용

애플리케이션이 이벤트를 처리하지 않고 탭에 응답할 ImageButtonClicked 있습니다. 명령 ImageButton 또는 명령 인터페이스라는 대체 알림 메커니즘을 구현합니다. 이 속성은 다음 두 가지 속성으로 구성됩니다.

이 방법은 데이터 바인딩과 관련하여, 특히 MVVM(Model-View-ViewModel) 아키텍처를 구현할 때 적합합니다.

명령 인터페이스 사용에 대한 자세한 내용은 단추 가이드에서 명령 인터페이스 사용을 참조하세요.

ImageButton 누르기 및 해제

Clicked 이벤트 외에도 ImageButtonPressedReleased 이벤트도 정의합니다. 이 Pressed 이벤트는 손가락을 눌렀 ImageButton거나 포인터를 포인터 위에 놓아 마우스 단추를 누를 때 발생합니다 ImageButton. 이 Released 이벤트는 손가락 또는 마우스 단추를 놓을 때 발생합니다. 일반적으로 Clicked 이벤트는 이벤트와 Released 동시에 발생하지만 손가락 또는 마우스 포인터가 놓 Clicked 이기 전의 ImageButton 표면에서 멀어지면 이벤트가 발생하지 않을 수 있습니다.

이러한 이벤트에 대한 자세한 내용은 단추 가이드에서 단추 누르기 및 해제를 참조하세요.

ImageButton 모양

클래스 ImageButton 에서 상속되는 ImageButton 속성 외에도 모양에 View 영향을 주는 몇 가지 속성을 정의합니다.

  • Aspect 은 표시 영역에 맞게 이미지의 크기를 조정하는 방법입니다.
  • BorderColor 은 을 둘러싼 영역의 색입니다 ImageButton.
  • BorderWidth 는 테두리의 너비입니다.
  • CornerRadius 는 .의 모퉁이 반경입니다 ImageButton.

이 속성은 Aspect 열거형의 Aspect 멤버 중 하나로 설정할 수 있습니다.

  • Fill - 이미지를 완전히 정확하게 채우도록 늘입니다 ImageButton. 이로 인해 이미지가 왜곡될 수 있습니다.
  • AspectFill - 가로 세로 비율을 유지하면서 채우도록 이미지를 클리핑합니다 ImageButton .
  • AspectFit - 이미지의 너비 또는 높이에 따라 위쪽/아래쪽 또는 측면에 빈 공간이 추가된 상태에서 전체 이미지가 이미지에 맞 ImageButton도록 이미지(필요한 경우)를 편지함으로 만듭니다. 열거형의 Aspect 기본값입니다.

참고 항목

클래스에는 ImageButtonMargin .의 ImageButton레이아웃 동작을 제어하는 속성도 있습니다Padding. 자세한 내용은 여백 및 패딩을 참조하세요.

ImageButton 시각적 상태

ImageButtonPressedVisualState 에는 사용자가 누를 때 시각적 변경을 ImageButton 시작하는 데 사용할 수 있는 기능이 있습니다.

다음 XAML 예제에서는 상태에 대한 Pressed 시각적 상태를 정의하는 방법을 보여줍니다.

<ImageButton Source="XamarinLogo.png"
             ...>
    <VisualStateManager.VisualStateGroups>
        <VisualStateGroup x:Name="CommonStates">
            <VisualState x:Name="Normal">
                <VisualState.Setters>
                    <Setter Property="Scale"
                            Value="1" />
                </VisualState.Setters>
            </VisualState>

            <VisualState x:Name="Pressed">
                <VisualState.Setters>
                    <Setter Property="Scale"
                            Value="0.8" />
                </VisualState.Setters>
            </VisualState>

        </VisualStateGroup>
    </VisualStateManager.VisualStateGroups>
</ImageButton>

PressedVisualState 눌렀을 ImageButton 때 해당 Scale 속성이 기본값 1에서 0.8로 변경되도록 지정합니다. 이 NormalVisualState 속성은 정상 상태일 때 ImageButton 해당 Scale 속성이 1로 설정되도록 지정합니다. 따라서 전반적인 효과는 누를 때 ImageButton 크기가 약간 더 작게 조정되고 ImageButton 릴리스되면 기본 크기로 다시 크기가 조정된다는 것입니다.

시각적 상태에 대한 자세한 내용은 Visual State Manager를 참조 Xamarin.Forms 하세요.