반응형

일반적으로 올리는 UWP 소스는 C#, XAML 을 기준으로 합니다.

 

잘못된 부분이 있거나 궁금하신게 있으면 댓글 달아주세요

 

 

 

오늘은 UWP로 windows10 OS를 사용하는 PC, 노트북에 연결된 웹 카메라의 화면을 불러오는 방법과

추가적으로 불러온 웹 캠 화면의 이동과 크기조절을 할 수 있는 예제를 올려본다

 

 

웹카메라를 불러올 때, 종료할 때 각각 Loading, Closing 텍스트 문구를 추가해서 진행 상태를 표기했다.

캠화면 크기 조절 시의 비율은 ScaleX, ScaleY를 각각 1.0으로 주어 가로, 세로 동시에 1:1 비율로 늘어나게 함

캠 화면을 불러올 때 Captureelement의 stretch속성을 fill로 주어서 개체에 꽉찬 화면으로 보이게했다

 

+캠 이동 중 화면 밖으로 나간 경우, 화면 테두리에 쿠션을 주어 막는 방법 대신

캠화면을 다시 불러왔을 때 고정 좌표에 카메라 화면을 띄우도록했다.

 

 

코드 보기 앞서

UI 조작 관련 내용이 낯선 사람들은 내가 이해한 대로 간략하게 적어봤으니 참고하길 바람

 

개체에 대한 이동, 크기조절, 회전 등의 조작을 가능하게 하는 것 - ManipulationDelta

개체에 대한 크기 조절 - RenderTransform

 

 

 

cs 코드

using System;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

using Windows.UI.Popups; // 팝업 메세지
using Windows.Media.Capture; //카메라 화면
using Windows.UI.Xaml.Media; //카메라 화면 UI 이동
using Windows.UI.Xaml.Input; //카메라 화면 UI 이동, 조작 시

// 빈 페이지 항목 템플릿에 대한 설명은 https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x412에 나와 있습니다.

namespace test
{
    /// <summary>
    /// 자체적으로 사용하거나 프레임 내에서 탐색할 수 있는 빈 페이지입니다.
    /// </summary>
    public sealed partial class MainPage : Page
    {
        int Cam_switch = 0;

        MediaCapture _mediaCapture = new MediaCapture();

        private TranslateTransform dragTranslation;

        public MainPage()
        {
            this.InitializeComponent();

            Cam_grid.Visibility = Visibility.Collapsed;

            dragTranslation = new TranslateTransform();
            Cam_grid.ManipulationDelta += Cam_grid_ManipulationDelta;            
            Cam_grid.RenderTransform = this.dragTranslation;
        }

        async private void Webcam_Click(object sender, RoutedEventArgs e)
        {
            if (Cam_switch == 0)
            {
                var devices = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(Windows.Devices.Enumeration.DeviceClass.VideoCapture);

                if (devices.Count < 1)
                {
                    var msg_cam = new MessageDialog("연결된 카메라가 없습니다");
                    await msg_cam.ShowAsync();
                    return;
                }
                else
                {
                    _mediaCapture = new MediaCapture();

                    try
                    {
                        dragTranslation.X = 5;
                        dragTranslation.Y = 5;

                        Cam_close.Visibility = Visibility.Collapsed;
                        Cam_grid.Visibility = Visibility.Visible;
                        Cam_load.Visibility = Visibility.Visible;

                        await _mediaCapture.InitializeAsync();

                        PreviewControl.Source = _mediaCapture;

                        await _mediaCapture.StartPreviewAsync();

                        Cam_switch = 1;

                        Cam_load.Visibility = Visibility.Collapsed;
                    }

                    catch (System.Exception)
                    {
                    }
                }
            }
            else
            {
                dragTranslation.X = 5;
                dragTranslation.Y = 5;

                Cam_close.Visibility = Visibility.Visible;
                PreviewControl.Source = null;
                await _mediaCapture.StopPreviewAsync();

                Cam_grid.Visibility = Visibility.Collapsed;

                Cam_switch = 0;

                Cam_scale.ScaleX = 1;
                Cam_scale.ScaleY = 1;
                Cam_bd_scale.ScaleX = 1;
                Cam_bd_scale.ScaleY = 1;

            }
        }

        private void Cam_grid_ManipulationDelta(object sender, ManipulationDeltaRoutedEventArgs e)
        {
            dragTranslation.X += e.Delta.Translation.X;
            dragTranslation.Y += e.Delta.Translation.Y;
            Cam_scale.ScaleX *= e.Delta.Scale;
            Cam_scale.ScaleY *= e.Delta.Scale;
            Cam_bd_scale.ScaleX *= e.Delta.Scale;
            Cam_bd_scale.ScaleY *= e.Delta.Scale;
        }
    }
}

 

 웹 캠 화면을 닫고나서 PreviewControl.Source (=리소스)를 null로 줌

 

 

 

 

xaml 코드

 

<Page
    x:Class="test.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:test"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

    <Grid>
        <Button x:Name="Webcam" Click="Webcam_Click">
            <SymbolIcon Symbol="Camera"></SymbolIcon>
        </Button>
        <Grid Name="Cam_grid"  Margin="0,49,0,0" CanDrag="False" Canvas.ZIndex="11" VerticalAlignment="Top" ManipulationMode="All" Width="420" Height="350"  HorizontalAlignment="Left" >
            <TextBox Name="Cam_load" Text="Loading..."/>
            <CaptureElement   Name="PreviewControl"  CanDrag="False" Stretch="Fill" ManipulationMode="All" >
                <CaptureElement.RenderTransform>
                    <ScaleTransform x:Name="Cam_scale" ScaleX="1.0" ScaleY="1.0" />
                </CaptureElement.RenderTransform>
            </CaptureElement>
            <Border BorderBrush="SkyBlue" BorderThickness="2" >
                <Border.RenderTransform>
                    <ScaleTransform x:Name="Cam_bd_scale" ScaleX="1.0" ScaleY="1.0" />
                </Border.RenderTransform>
            </Border>
            <TextBox Name="Cam_close" Text="Closing..." />
        </Grid>
    </Grid>
</Page>

 

 

예시 사진

 

먼저 카메라에 접근하기 위해서는 어플리케이션을 다운받고 연락처나 카메라 접근 허가해주듯 허가 요청에 대한

명시가 따로 필요한데 이것을 manifest라고 부름

 

따라서 UWP 또한 접근할 기능에 대한 앱 매니페스토 허용이 필요하여 우측의 솔루션 탐색기에서

Package.appxmanifest 파일을 더블클릭하여 수정을 해주면된다

 

솔루션에 위치한 appxmanifest 더블 클릭

 

UWP 앱 매니페스트 화면

상단의 기능탭을 클릭하여 웹캠, 마이크를 체크해준 다음 프로그램 빌드/디버그를 진행해서 테스트하면 된다.

 

 

 

 

웹 카메라 화면 불러오기 메인화면

실행 시 카메라 아이콘을 입혀둔 버튼을 확인할 수 있다

아담한 저 버튼을 클릭하면 연결한 웹캠의 화면이 이제 나타난다

 

 

매니페스트 액세스 허용

 

버튼 클릭 후 액세스 허용을 해준다면 말이지

 

 

 

 

 

 

웹 카메라 화면 로딩 중

액세스 허용 시 나타나는 화면

 

 

 

 

웹캠 화면 불러온 상태

 

불러온 웹카메라 화면 이동한 상태

불러온 카메라 리소스를 이동시켜줌

 

 

 

캠화면 닫기

 

 

+연결된 카메라를 확인 후 카메라 연결이 없을 때 나타나는 팝업 창

 

카메라 연결이 없는 경우 팝업

 

 

 

 

 

앞에서 허용해준 앱 액세스 값 변경하는 법

 

 

윈도우의 기본 설정값을 변경해주면 된다

과정은 다음과 같으니 액세스 허용 후에 관한 변경사항이 필요할 경우, 참고하길 바람

 

 

 

 

 

 

 

 

 

 

 

 

 

참고사이트

docs.microsoft.com/ko-kr/windows/uwp/audio-video-camera/basic-photo-video-and-audio-capture-with-mediacapture

 

MediaCapture를 사용하여 기본적인 사진, 비디오 및 오디오 캡처 - UWP applications

이 문서에서는 MediaCapture 클래스를 사용 하 여 사진과 비디오를 캡처하는 가장 간단한 방법을 보여 줍니다.

docs.microsoft.com

 

반응형
반응형

 

지금이야 익숙해져서 뚝딱해서 프로젝트를 시작할 수 있지만

처음 uwp를 접했을때는 버전도 골라야해서 약간 막막함이 있었다

 

그래서 아예 이미지로 정리해봤음

 

※이 글은 C#, Xaml을 이용하여 UWP를 시작하려는 사람에게 최적화 되어있습니다

 

 

UWP (Universal Windows Platform)

목적 : 윈도우 10, 윈도우 10 모바일, 엑스박스 원, 홀로렌즈에서 실행할 유니버셜 앱의 개발을 돕기 위해 제작되어짐

윈도우 10 OS로 구동되는 디바이스에서 사용이 가능한 앱

 

※유니버설 앱(Universal App) : 하나의 프로젝트에서 개발한, 데스크톱, 모바일, 태블릿 등 모든 기기와 운영체제를 아우르는 서비스 또는 앱을 의미

ex) 한 번 개발하면 화면 크기에 따라 UI가 자동으로 변하고, 디스플레이 크기와 기기에 따른 파편화된 사용자 경험을 합칠 수 있다는 장점이 있다.

 

 

지원 개발 언어

  • XAML UI 및 C#, VB 또는 C++
  • DirectX UI 및 C++
  • JavaScript 및 HTML
  • WinUI

 

 

 

 

 

Visual C# 클릭 후 비어있는 앱 (유니버셜 Windows) 선택

 

대상버전은 1809와 최소버전은 Creators Update인 15063을 사용하고 있는데

처음 uwp를 다룰 때 이 최소버전 지정을 잘못해서 피시에서 실행이 안된적이 있었어서

요즘은 이렇게 주로 하고있다 원래 사용했던 버전에서 윈도우 업데이트 이후 문제가 생긴다면

웬만하면 버전 관련 문제일 확률이 높다

 

자세한 사항이 궁금하면 좌측 하단부에 있는 버전 선택에 대한 설명이 있으니 아래 사이트를 참고하자

 

docs.microsoft.com/ko-kr/windows/uwp/updates-and-versions/choose-a-uwp-version?ocid=VSClient_VerX_NewProject_version

 

UWP 버전 선택 - UWP applications

Microsoft Visual Studio에서 UWP 앱을 작성하는 경우 대상 버전을 선택할 수 있습니다. 다른 UWP 버전 간 차이점과 새 프로젝트 및 기존 프로젝트에서 선택을 구성하는 방법을 알아봅니다.

docs.microsoft.com

 

 

주로 이런 설명이 있으니 업데이트 버전을 대략적으로 파악하기에 좋을듯하다 (아직은 잘 모르겠음)

 

 

버전을 지정하고 확인을 누르면 프로젝트가 생성된 모습을 확인할 수 있음

 

프로젝트 생성이 완료되어 우측의 솔루션 탐색기를 이용해서 MainPage.xaml, MainPage.xaml.cs 의 코드에 접근이

가능하니 이제 예제를 따라하거나 만들어보고 싶은걸 시작해보면 되겠다

 

 

 

참고 사이트

 

www.itworld.co.kr/news/95019

 

ITWorld 용어풀이 | 유니버설 앱

유니버설 앱(Universal App)은 하나의 프로젝트에서 개발한, 데스크톱, 모바일, 태블릿 등 모든 기기와 운영체제를 아우르는 서비스 또는 앱을 의미합니다. 한 번 개발하면 화면 크기에 따라 UI가 자

www.itworld.co.kr

docs.microsoft.com/ko-kr/windows/uwp/get-started/universal-application-platform-guide

 

UWP(유니버설 Windows 플랫폼) 앱이란? - UWP applications

이 가이드에서는 Windows 10을 실행하는 다양한 디바이스에서 실행할 수 있는 UWP(유니버설 Windows 플랫폼) 앱에 대해 알아봅니다.

docs.microsoft.com

 

반응형
반응형

일반적으로 올리는 UWP 소스는 C#, XAML 을 기준으로 합니다.

 

잘못된 부분이 있거나 궁금하신게 있으면 댓글 달아주세요

 

UWP에서 이미지 불러오는걸 구현한 예제

이미지를 불러올 때는 기존과 다르게 버튼만으로 구현하게 아니라 플라이 아웃 메뉴라고

클릭 시 버튼들이 주르륵 목록화 되어 나오는걸로 구현해봄

조금 귀찮고 이거보다도 더 멋지게 할수있지만 그냥 간단하게 클릭했을 때 늘어나는 메뉴를 해보고싶어서 추가함

 

이미지 위에 불러온 이미지를 닫는 버튼이 있고 이 버튼 위에 마우스 호버링이 이루어지면 버튼의 색상을 투명화되게끔 추가함

 

 

 

 

using System;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives; //FlyoutBase
using Windows.UI.Xaml.Input; //UI 이동
using Windows.UI.Xaml.Media; 

// 빈 페이지 항목 템플릿에 대한 설명은 https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x412에 나와 있습니다.

namespace testing
{
    /// <summary>
    /// 자체적으로 사용하거나 프레임 내에서 탐색할 수 있는 빈 페이지입니다.
    /// </summary>
    public sealed partial class MainPage : Page
    {

        int Img_open_switch = 0;

        //앱바 메뉴
        int Bar_menu_switch = 0;

        public MainPage()
        {
            this.InitializeComponent();

        }
        
        private void Media_menu_Click(object sender, RoutedEventArgs e)
        {
            FlyoutBase.ShowAttachedFlyout((FrameworkElement)sender);
        }      

        //이미지 불러오기
        private async void IMG_open_Click(object sender, RoutedEventArgs e)
        {
            if (Img_open_switch == 0)
            {
                var picker = new Windows.Storage.Pickers.FileOpenPicker
                {
                    ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail,
                    SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary
                };

                picker.FileTypeFilter.Add(".jpg");
                picker.FileTypeFilter.Add(".jpeg");
                picker.FileTypeFilter.Add(".png");
                picker.FileTypeFilter.Add(".bmp");
                picker.FileTypeFilter.Add(".gif");

                Windows.Storage.StorageFile file = await picker.PickSingleFileAsync();
                if (file != null)
                {                 
                    if (!IMG_G.IsOpen) { IMG_G.IsOpen = true; }
                    // Application now has read/write access to the picked file
                    using (Windows.Storage.Streams.IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read))
                    {
                        // Set the image source to the selected bitmap 
                        Windows.UI.Xaml.Media.Imaging.BitmapImage bitmapImage = new Windows.UI.Xaml.Media.Imaging.BitmapImage
                        {
                            DecodePixelWidth = 600 //리소스를 줄이기 위한 픽셀고정(최대 720)
                        };
                        await bitmapImage.SetSourceAsync(fileStream);
                        img.Source = bitmapImage;

                        IMG_C.Visibility = Visibility.Visible;
                    }
                }
                else
                {
                }

                Img_open_switch = 1;
            }

            //이미지 닫는 부분 추가
            else
            {
                img.Source = null;
                IMG_C.Visibility = Visibility.Collapsed;

                if (IMG_G.IsOpen) { IMG_G.IsOpen = false; }
                
                Img_open_switch = 0;
            }
        }

        //이미지 닫기
        async private void IMG_C_Click(object sender, RoutedEventArgs e)
        {            
            img.Source = null;
            IMG_C.Visibility = Visibility.Collapsed;

            Img_open_switch = 0;

            if (IMG_G.IsOpen) { IMG_G.IsOpen = false; }
        }

    }
}

 

 

 

Xaml 코드

 

<Page
    x:Class="testing.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:testing"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

    <Page.Resources>
        <DataTemplate x:Key="ImageTemplate">
            <Grid>
                <Image Source="{Binding}" />
            </Grid>
        </DataTemplate>


        <!--메뉴 이미지 flyout-->

        <MenuFlyout x:Key="media_flyout">
            <MenuFlyoutItem Text="이미지" Click="IMG_open_Click" />
        </MenuFlyout>        
    </Page.Resources>
    
    
    <Grid>
        <StackPanel Orientation="Horizontal" Canvas.ZIndex="100" VerticalAlignment="Bottom" HorizontalAlignment="Center" >
            <CommandBar x:Name="Menu_bar" VerticalAlignment="Bottom"  HorizontalAlignment="Center" Canvas.ZIndex="100">
                <AppBarButton FlyoutBase.AttachedFlyout="{StaticResource media_flyout}" Click="Media_menu_Click" ToolTipService.ToolTip="미디어 오픈" Icon="Attach" />    
            </CommandBar>            
        </StackPanel>

        <!--이미지 닫기-->
        <Popup x:Name="IMG_G"  ManipulationMode="All" Canvas.ZIndex="5" Width="auto" Height="auto"  >
            <Grid x:Name="Img_save" ManipulationDelta="Img_ManipulationDelta">
                    <Image Canvas.ZIndex="6" VerticalAlignment="Top" HorizontalAlignment="Left" x:Name="img" ManipulationMode="All" Stretch="UniformToFill" Height="auto" Width="auto" >
                        <Image.RenderTransform>
                            <ScaleTransform x:Name="ScaleTransform" ScaleX="1.0" ScaleY="1.0"/>
                        </Image.RenderTransform>
                    </Image>

                <StackPanel Canvas.ZIndex="7" VerticalAlignment="Top" HorizontalAlignment="Left" Orientation="Horizontal">
                    <Button x:Name="IMG_C" Canvas.ZIndex="8" Background="White"  VerticalAlignment="Top" HorizontalAlignment="Left" Click="IMG_C_Click"  Width="65"  Height="65" >
                        <SymbolIcon Symbol="Cancel"/>
                    </Button>
                </StackPanel>
            </Grid>                
            
        </Popup>
    </Grid>
</Page>

 

 

예시 사진

 

 

 

이미지 닫는 버튼 위에 마우스를 올리면 색상이 바뀌는것도 적용시킴

 

 

반응형
반응형

일반적으로 올리는 UWP 소스는 C#, XAML 을 기준으로 합니다.

 

잘못된 부분이 있거나 궁금하신게 있으면 댓글 달아주세요

 

 

UWP 사용 시 입력한 인터넷 주소에 접속하여 기본적인 페이지의 기능을 모두 사용할수있고

주소창 입력이 가능하여 다른 페이지로의 이동이 가능한 기능인 웹뷰를 사용할수있는 예제

 

 

웹 뷰창을 닫을 수 있고 입력한 주소로 이동이 가능하게 버튼을 추가해봄

자세한 사항은 아래 첨부된 코드를 확인해주세여

 

 

 

CS 코드

 

using System;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

using Windows.UI.Xaml.Media; //UI 이동

// 빈 페이지 항목 템플릿에 대한 설명은 https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x412에 나와 있습니다.

namespace testing
{
    /// <summary>
    /// 자체적으로 사용하거나 프레임 내에서 탐색할 수 있는 빈 페이지입니다.
    /// </summary>
    public sealed partial class MainPage : Page
    {

        //웹 뷰 on/off 확인 변수
        int Web_View_switch = 0;


        public MainPage()
        {
            this.InitializeComponent();
            
        }

        // 웹뷰 인터넷 사용 클릭 = 브라우저 팝업 창 뜸
        async private void Web_view_Click(object sender, RoutedEventArgs e)
        {
            if (Web_View_switch == 0)
            {
                Web_View_switch = 1;
                Web_view.Visibility = Visibility.Visible;
                
            }
            //웹뷰 닫기
            else
            {
                Web_view.Visibility = Visibility.Collapsed;

                //tbxURL.Text = "";
                String sURL = "http://www.naver.com/";
                Uri webURL = new Uri(sURL);
                ctlBrowser.Navigate(webURL);

                Web_View_switch = 0;
            }
        }


        // 웹뷰 주소창 이동
        private void Web_Start_Click(object sender, RoutedEventArgs e)
        {
            String sURL = tbxURL.Text;
            if (sURL.IndexOf("http://") == -1) { sURL = "http://" + sURL; }

            try
            {
                Uri webURL = new Uri(sURL);
                ctlBrowser.Navigate(webURL);
            }
            catch (Exception)
            {
                // throw;
            }
        }

        // 웹뷰 주소창
        private void CtlBrowser_NavigationStarting(WebView sender, WebViewNavigationStartingEventArgs args)
        {
            ctlProgress.IsActive = true;
        }

        private void CtlBrowser_NavigationCompleted(WebView sender, WebViewNavigationCompletedEventArgs args)
        {
            ctlProgress.IsActive = false;
        }
        
        //웹뷰 인터넷 닫기
        private void Web_C_Click(object sender, RoutedEventArgs e)
        {
            Web_view.Visibility = Visibility.Collapsed;

            //tbxURL.Text = "";
            String sURL = "http://www.naver.com/";
            Uri webURL = new Uri(sURL);
            ctlBrowser.Navigate(webURL);
            

            Web_View_switch = 0;           
        }
        
    }
}

 

 

 

XAML 코드

<Page
    x:Class="testing.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:testing"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

    <Grid>
        <Button x:Name="webView" Click="Web_view_Click">웹뷰 열기</Button>
        <TextBlock Width="1" Height="1" VerticalAlignment="Top" HorizontalAlignment="Right" x:Name="textBlock" ></TextBlock>

        <!--웹뷰-->        
        <StackPanel x:Name="Web_view" Canvas.ZIndex="6">
            <StackPanel x:Name="Web_menu" Height="50" Grid.Row="0" Orientation="Horizontal"  HorizontalAlignment="Stretch"  VerticalAlignment="Stretch" Background="Gainsboro" >
                <!--<Grid x:Name="Web_menu">-->
                <Image Source="Assets/5url.png" Width="60" Height="50" Stretch="Uniform" />

                <TextBox  x:Name="tbxURL" Text="http://"  Width="500" Background="White" BorderBrush="#8d8d8d" BorderThickness="1" Padding="5" ToolTipService.ToolTip="URL 작성" />
                <Button x:Name="Web_Start" ToolTipService.ToolTip="입력 URL로 이동" Height="auto" Click="Web_Start_Click">                    
                    <SymbolIcon Symbol="Forward"/>
                </Button>                
                <Button x:Name="Web_C" Click="Web_C_Click" ToolTipService.ToolTip="웹 종료">                    
                    <SymbolIcon Symbol="Cancel"/>
                </Button>
                <ProgressRing x:Name="ctlProgress" Height="30" Width="30" />
                <!--</Grid>-->
            </StackPanel>
            <WebView x:Name="ctlBrowser" NavigationStarting="CtlBrowser_NavigationStarting" NavigationCompleted="CtlBrowser_NavigationCompleted" Source="http://www.naver.com/" Height="1026" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" />
        </StackPanel>

    </Grid>
</Page>

 

XAML 에는 버튼에 아이콘을 삽입해보았다

생각보다 간단하게 UWP 기본 제공 심플 아이콘을 입힐수 있으니 모두들 사용해보자

 

 

아래는 사용 예제 이미지 첨부

->  클릭 시 입력한 주소로 웹페이지 이동

X 클릭 시 웹뷰 화면 닫기 가능

웹뷰 닫은 뒤 열기 클릭 시 웹뷰 화면 다시 불러와짐

 

반응형
반응형

일반적으로 올리는 UWP 소스는 C#, XAML 을 기준으로 합니다.

 

잘못된 부분이 있거나 궁금하신게 있으면 댓글 달아주세요

 

기존 올린 예제에 불러온 동영상 파일의 위치 이동 및 크기 조절이 가능한 기능을 덧붙인 예제입니다.

이때, 크기조절은 터치가 가능한 터치 모니터, 스크린에서만 가능합니다

 

 

CS

using System;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

using Windows.UI.Xaml.Media; //UI 이동

// 빈 페이지 항목 템플릿에 대한 설명은 https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x412에 나와 있습니다.

namespace testing
{
    /// <summary>
    /// 자체적으로 사용하거나 프레임 내에서 탐색할 수 있는 빈 페이지입니다.
    /// </summary>
    public sealed partial class MainPage : Page
    {
        //동영상 on,off 변수
        int Mov_open_switch = 0;

        //동영상 이동
        private TranslateTransform dragTranslation_M;

        

        public MainPage()
        {
            this.InitializeComponent();

            //동영상 이동
            dragTranslation_M = new TranslateTransform();
            MediaPlayerPopup.ManipulationDelta += MediaPlayerPopup_ManipulationDelta;
            MediaPlayerPopup.RenderTransform = this.dragTranslation_M;

            //동영상 트랙바
            MOV.AreTransportControlsEnabled = false;

        }


        private async void Media_open_Click(object sender, RoutedEventArgs e)
        {
            if (Mov_open_switch == 0)
            {
                var openPicker = new Windows.Storage.Pickers.FileOpenPicker();

                openPicker.FileTypeFilter.Add(".wmv");
                openPicker.FileTypeFilter.Add(".mp4");
                openPicker.FileTypeFilter.Add(".wma");
                openPicker.FileTypeFilter.Add(".mp3");
                openPicker.FileTypeFilter.Add(".avi");


                var file = await openPicker.PickSingleFileAsync();

                // mediaPlayer is M_right MediaElement defined in XAML
                if (file != null)
                {
                    if (!MediaPlayerPopup.IsOpen) { MediaPlayerPopup.IsOpen = true; }
                    var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
                    MOV.SetSource(stream, file.ContentType);
                    MOV.AreTransportControlsEnabled = true;
                    MOV.TransportControls.IsZoomButtonVisible = true;
                    MOV.TransportControls.IsZoomEnabled = true;

                    MOV_C.Visibility = Visibility.Visible;
                    Mov_open_switch = 1;
                    MOV.Play();
                }
                else
                {
                    this.textBlock.Text = "Operation cancelled.";
                    Mov_open_switch = 0;
                    return;

                }

            }
            //동영상 닫기
            else
            {
                Mov_open_switch = 0;
                if (MediaPlayerPopup.IsOpen) { MediaPlayerPopup.IsOpen = false; }
                dragTranslation_M.X = 0;
                dragTranslation_M.Y = 0;
            }
        }

        // 동영상 닫기
        private void MOV_C_Click(object sender, RoutedEventArgs e)
        {
            if (MediaPlayerPopup.IsOpen) { MediaPlayerPopup.IsOpen = false; }
            Mov_open_switch = 0;
            dragTranslation_M.X = 0;
            dragTranslation_M.Y = 0;
        }
        
        private void OnMEFullWindowChanged(DependencyObject sender, DependencyProperty dp)
        {
            MediaElement me = (MediaElement)sender;

            if (me != null && dp == MediaElement.IsFullWindowProperty)
            {
                if (me.IsFullWindow == true)
                {
                    MediaPlayerPopup.Visibility = Visibility.Collapsed;
                }
                else
                {
                    MediaPlayerPopup.Visibility = Visibility.Visible;
                }
            }
        }


        

        //동영상 크기조절
        private void MOV_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            MediaPlayerPopup.Width = Window.Current.Bounds.Width;
            MediaPlayerPopup.Height = Window.Current.Bounds.Height;
        }

        private void MediaPlayerPopup_ManipulationDelta(object sender, Windows.UI.Xaml.Input.ManipulationDeltaRoutedEventArgs e)
        {
            dragTranslation_M.X += e.Delta.Translation.X;
            dragTranslation_M.Y += e.Delta.Translation.Y;
            //동영상 크기조절
            ScaleTransformm.ScaleX *= e.Delta.Scale;
            ScaleTransformm.ScaleY *= e.Delta.Scale;
        }
    }
}

 

 

XAML

<Page
    x:Class="testing.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:testing"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

    <Grid>
        <Button x:Name="openMedia" Click="Media_open_Click">동영상 불러오기</Button>
        <TextBlock Width="1" Height="1" VerticalAlignment="Top" HorizontalAlignment="Right" x:Name="textBlock" ></TextBlock>
        <!--동영상-->
        <Popup x:Name="MediaPlayerPopup" VerticalAlignment="Top" HorizontalAlignment="Left" Canvas.ZIndex="5"  Width="720" Height="405"  ManipulationMode="All" >
            <!--VerticalAlignment="Bottom" HorizontalAlignment="Center"-->
            <Grid >
                <Grid ManipulationDelta="MediaPlayerPopup_ManipulationDelta" ManipulationMode="Scale">
                    <MediaElement x:Name="MOV" SizeChanged="MOV_SizeChanged" AreTransportControlsEnabled="True" Height="405" Width="720" ManipulationMode="All" >                        
                        <MediaElement.RenderTransform>
                            <ScaleTransform x:Name="ScaleTransformm" ScaleX="1.0" ScaleY="1.0"/>
                        </MediaElement.RenderTransform>
                    </MediaElement>
                </Grid>
                <!--동영상 닫기-->
                <Button x:Name="MOV_C" Background="White" Click="MOV_C_Click" VerticalAlignment="Top" HorizontalAlignment="Left" >
                    <SymbolIcon Symbol="Cancel"/>
                </Button>
            </Grid>
        </Popup>
    </Grid>
</Page>

 

ScaleX, ScaleY의 값에 1.0, 1.5 등을 넣음으로써 크기 조절 시 가로, 세로 증감하는 길이에 대한 비율을 정할 수 있다

 

 

 

위의 코드 실행 이미지

 

 

동영상을 가운데로 이동 후 작게 줄여봄

 

 

 

참고 사이트

 

docs.microsoft.com/en-us/uwp/api/windows.ui.xaml.media.scaletransform?view=winrt-19041

 

ScaleTransform Class (Windows.UI.Xaml.Media) - Windows UWP applications

Scales an object in the two-dimensional x-y coordinate system.

docs.microsoft.com

 

반응형
반응형

일반적으로 올리는 UWP 소스는 C#, XAML 을 기준으로 합니다.

 

잘못된 부분이 있거나 궁금하신게 있으면 댓글 달아주세요

 

 

MediaPlayerElement 클래스 사용한 동영상 파일 (음성 파일 포함) 불러오기 예제 코드에 이거저거 덧붙여봄

 

기본적인 기능으로는 내 PC에 있는 동영상 파일을 불러올 수 있습니다

 

예제 코드에 추가한 내용으로는 트랙바 추가, 동영상 오픈 시 자동 재생, 동영상 닫기 버튼입니다

 

MainPage.xaml.cs

 

using System;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

namespace testing
{
    /// <summary>
    /// 자체적으로 사용하거나 프레임 내에서 탐색할 수 있는 빈 페이지입니다.
    /// </summary>
    public sealed partial class MainPage : Page
    {
        //동영상 on,off 변수
        int Mov_open_switch = 0;

        public MainPage()
        {
            this.InitializeComponent();
        }


        private async void Media_open_Click(object sender, RoutedEventArgs e)
        {
            if (Mov_open_switch == 0)
            {
            	
                var openPicker = new Windows.Storage.Pickers.FileOpenPicker();

                openPicker.FileTypeFilter.Add(".wmv");
                openPicker.FileTypeFilter.Add(".mp4");
                openPicker.FileTypeFilter.Add(".wma");
                openPicker.FileTypeFilter.Add(".mp3");
                openPicker.FileTypeFilter.Add(".avi");


                var file = await openPicker.PickSingleFileAsync();

                // mediaPlayer is M_right MediaElement defined in XAML
                if (file != null)
                {
                    if (!MediaPlayerPopup.IsOpen) { MediaPlayerPopup.IsOpen = true; }
                    var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
                    MOV.SetSource(stream, file.ContentType);
                    MOV.AreTransportControlsEnabled = true;
                    MOV.TransportControls.IsZoomButtonVisible = true;
                    MOV.TransportControls.IsZoomEnabled = true;

                    MOV_C.Visibility = Visibility.Visible;
                    Mov_open_switch = 1;
                    MOV.Play();
                }
                else
                {
                	//파일 불러오기 실패한 경우
                    this.textBlock.Text = "Operation cancelled.";
                    Mov_open_switch = 0;
                    return;
                }

            }
            //동영상 닫기 - 동영상 불러오기 한번 더 클릭 시 닫기
            else
            {
                Mov_open_switch = 0;
                if (MediaPlayerPopup.IsOpen) { MediaPlayerPopup.IsOpen = false; }
            }
        }


        // 동영상 닫기
        private void MOV_C_Click(object sender, RoutedEventArgs e)
        {
            if (MediaPlayerPopup.IsOpen) { MediaPlayerPopup.IsOpen = false; }
            Mov_open_switch = 0;
        }

    }
}

 

MainPage.xaml

<Page
    x:Class="testing.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:testing"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

    <Grid>
        <Button x:Name="openMedia" Click="Media_open_Click">동영상 불러오기</Button>
        <TextBlock Width="1" Height="1" VerticalAlignment="Top" HorizontalAlignment="Right" x:Name="textBlock" ></TextBlock>
        <!--동영상-->
        <Popup x:Name="MediaPlayerPopup" VerticalAlignment="Top" HorizontalAlignment="Left" Canvas.ZIndex="5"  Width="720" Height="405">            
            <Grid >                
                <MediaElement x:Name="MOV" AreTransportControlsEnabled="True" Height="405" Width="720" >                    
                </MediaElement>                
                <!--동영상 닫기-->
                <Button x:Name="MOV_C" Background="White" Click="MOV_C_Click" VerticalAlignment="Top" HorizontalAlignment="Left" >
                    <SymbolIcon Symbol="Cancel"/>
                </Button>
            </Grid>
        </Popup>
    </Grid>
</Page>

 

실행 화면

 

 

 

 

 

 

참고 사이트

 

https://docs.microsoft.com/en-us/uwp/api/windows.ui.xaml.controls.mediaplayerelement?view=winrt-19041

 

MediaPlayerElement Class (Windows.UI.Xaml.Controls) - Windows UWP applications

Represents an object that uses a MediaPlayer to render audio and video to the display.

docs.microsoft.com

 

반응형

+ Recent posts