[C#/WPF] RenderOptions 클래스 : SetCachingHint 정적 메소드를 사용해 캐싱 힌트 옵션 설정하기
■ 기본적으로 WPF는 DrawingBrush 및 VisualBrush와 같은 TileBrush 개체의 렌더링된 콘텐츠를 캐시하지 않는다. 장면에서 TileBrush의 내용이나 사용이 변경되지 않는 정적 시나리오에서는 비디오
■ 기본적으로 WPF는 DrawingBrush 및 VisualBrush와 같은 TileBrush 개체의 렌더링된 콘텐츠를 캐시하지 않는다. 장면에서 TileBrush의 내용이나 사용이 변경되지 않는 정적 시나리오에서는 비디오
■ Image 엘리먼트의 FlowDirection 속성을 설정하는 방법을 보여준다. 다른 UI 요소와 달리 이미지는 컨테이너에서 FlowDirection을 상속하지 않는다. 그러나 FlowDirection이 명시적으로 RightToLeft로 설정되면
■ Image 객체에서 이미지의 RTF를 구하는 방법을 보여준다. ▶ 예제 코드 (C#)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 |
using System.Drawing.Imaging; using System.Runtime.InteropServices; using System.Text; #region 이미지 RTF 구하기 - GetImageRTF(image) /// <summary> /// 이미지 RTF 구하기 /// </summary> /// <param name="image">이미지</param> /// <returns>이미지 RTF</returns> public string GetImageRTF(Image image) { const int MM_ISOTROPIC = 7; // 메타 파일이 1:1 종횡비를 유지하는지 확인한다. const int MM_ANISOTROPIC = 8; // 메타 파일의 X 좌표와 Y 좌표를 독립적으로 조정할 수 있습니다. int mappingMode = MM_ANISOTROPIC; MemoryStream stream = null; Graphics graphics = null; Metafile metaFile = null; IntPtr deviceContextHandle; try { StringBuilder stringBuilder = new StringBuilder(); stream = new MemoryStream(); using(graphics = Graphics.FromHwnd(new IntPtr(0))) { deviceContextHandle = graphics.GetHdc(); metaFile = new Metafile(stream, deviceContextHandle); graphics.ReleaseHdc(deviceContextHandle); } using(graphics = Graphics.FromImage(metaFile)) { graphics.DrawImage(image, new Rectangle(0, 0, image.Width, image.Height)); } IntPtr emfHandle = metaFile.GetHenhmetafile(); uint bufferSize = GdipEmfToWmfBits(emfHandle, 0, null, mappingMode, EMFToWMFBitsFlag.Default); byte[] bufferByteArray = new byte[bufferSize]; GdipEmfToWmfBits(emfHandle, bufferSize, bufferByteArray, mappingMode, EMFToWMFBitsFlag.Default); for(int i = 0; i < bufferByteArray.Length; ++i) { stringBuilder.Append(string.Format("{0:X2}", bufferByteArray[i])); } return stringBuilder.ToString(); } finally { if(graphics != null) { graphics.Dispose(); } if(metaFile != null) { metaFile.Dispose(); } if(stream != null) { stream.Close(); } } } #endregion /// <summary> /// EMF→WMF 비트 플래그 /// </summary> public enum EMFToWMFBitsFlag { /// <summary> /// Default /// </summary> Default = 0x00000000, /// <summary> /// Embed EMF /// </summary> EmbedEMF = 0x00000001, /// <summary> /// Include Placeable /// </summary> IncludePlaceable = 0x00000002, /// <summary> /// No XOR Clip /// </summary> NoXORClip = 0x00000004 }; #region GDI+ EMF→WMF 변환하기 - GdipEmfToWmfBits(emfHandle, bufferSize, bufferByteArray, mappingMode, flag) /// <summary> /// GDI+ EMF→WMF 변환하기 /// </summary> /// <param name="emfHandle">EMF 핸들</param> /// <param name="bufferSize">버퍼 크기</param> /// <param name="bufferByteArray">버퍼 바이트 배열</param> /// <param name="mappingMode">매핑 모드</param> /// <param name="flag">플래그</param> /// <returns>처리 결과</returns> [DllImport("gdiplus")] private static extern uint GdipEmfToWmfBits(IntPtr emfHandle, uint bufferSize, byte[] bufferByteArray, int mappingMode, EMFToWMFBitsFlag flag); #endregion |
■ PNG 파일을 SVG 파일로 변환하는 방법을 보여준다. ▶ main.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 |
import sys import operator import logging import collections import io import optparse from PIL import Image ################################################################################ # 공통 ################################################################################ def AddTuple(tuple1, tuple2): return tuple(map(operator.add, tuple1, tuple2)) def SubtractTuple(tuple1, tuple2): return tuple(map(operator.sub, tuple1, tuple2)) def NegateTuple(tuple1): return tuple(map(operator.neg, tuple1)) def CalculateDirection(edgeTupleTuple): return SubtractTuple(edgeTupleTuple[1], edgeTupleTuple[0]) def CalculateMagnitude(a): return int(pow(pow(a[0], 2) + pow(a[1], 2), .5)) def Normalize(tuple1): magnitude = CalculateMagnitude(tuple1) assert magnitude > 0, "Cannot normalize a zero-length vector" return tuple(map(operator.truediv, tuple1, [magnitude] * len(tuple1))) def GetSVGHeader(width, height): return """<?xml version="1.0" encoding="UTF-8" standalone="no"?> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> <svg width="%d" height="%d" xmlns="http://www.w3.org/2000/svg" version="1.1"> """ % (width, height) ################################################################################ # SVG 데이터 구하기 1 ################################################################################ def GetJoinedEdgeList(assortedEdgeDictionary, keepEveryPoint = False): pieceListList = [] pieceList = [] directionDeque = collections.deque([(0, 1), (1, 0), (0, -1), (-1, 0)]) while assortedEdgeDictionary: if not pieceList: pieceList.append(assortedEdgeDictionary.pop()) currentDirectionTuple = Normalize(CalculateDirection(pieceList[-1])) while currentDirectionTuple != directionDeque[2]: directionDeque.rotate() for i in range(1, 4): nextEndTuple = AddTuple(pieceList[-1][1], directionDeque[i]) nextEdgeTuple = (pieceList[-1][1], nextEndTuple) if nextEdgeTuple in assortedEdgeDictionary: assortedEdgeDictionary.remove(nextEdgeTuple) if i == 2 and not keepEveryPoint: pieceList[-1] = (pieceList[-1][0], nextEdgeTuple[1]) else: pieceList.append(nextEdgeTuple) if pieceList[0][0] == pieceList[-1][1]: if not keepEveryPoint and Normalize(CalculateDirection(pieceList[0])) == Normalize(CalculateDirection(pieceList[-1])): pieceList[-1] = (pieceList[-1][0], pieceList.pop(0)[1]) pieceListList.append(pieceList) pieceList = [] break else: raise Exception("Failed to find connecting edge") return pieceListList def GetSVGData1(image, opaque = None, keepEveryPoint = False): adjacentOffsetTuple = ((1, 0), (0, 1), (-1, 0), (0, -1)) visitedImage = Image.new("1", image.size, 0) colorTupleDictionary = {} width, height = image.size for x in range(width): for y in range(height): pointTuple = (x, y) if visitedImage.getpixel(pointTuple): continue colorTuple = image.getpixel((x, y)) if opaque and not colorTuple[3]: continue pieceList = [] queueList = [pointTuple] visitedImage.putpixel(pointTuple, 1) while queueList: pointTuple = queueList.pop() for offsetTuple in adjacentOffsetTuple: neighbourPointTuple = AddTuple(pointTuple, offsetTuple) if not (0 <= neighbourPointTuple[0] < width) or not (0 <= neighbourPointTuple[1] < height): continue if visitedImage.getpixel(neighbourPointTuple): continue neighbourPointColorTuple = image.getpixel(neighbourPointTuple) if neighbourPointColorTuple != colorTuple: continue queueList.append(neighbourPointTuple) visitedImage.putpixel(neighbourPointTuple, 1) pieceList.append(pointTuple) if not colorTuple in colorTupleDictionary: colorTupleDictionary[colorTuple] = [] colorTupleDictionary[colorTuple].append(pieceList) del adjacentOffsetTuple del visitedImage edgeDictionray = \ { (-1, 0) : ((0, 0), (0, 1)), ( 0, 1) : ((0, 1), (1, 1)), ( 1, 0) : ((1, 1), (1, 0)), ( 0, -1) : ((1, 0), (0, 0)) } colorEdgeDictionary = {} for colorTuple, pieceList in colorTupleDictionary.items(): for piecePixelList in pieceList: edgeSet = set([]) for coordinateTuple in piecePixelList: for offsetTuple, (startOffsetTuple, endOffsetTuple) in edgeDictionray.items(): neighbourPointTuple = AddTuple(coordinateTuple, offsetTuple ) startTuple = AddTuple(coordinateTuple, startOffsetTuple) endTuple = AddTuple(coordinateTuple, endOffsetTuple ) edgeTuple = (startTuple, endTuple) if neighbourPointTuple in piecePixelList: continue edgeSet.add(edgeTuple) if not colorTuple in colorEdgeDictionary: colorEdgeDictionary[colorTuple] = [] colorEdgeDictionary[colorTuple].append(edgeSet) del colorTupleDictionary del edgeDictionray colorJoinedPieceDictionary = {} for colorTuple, pieceList in colorEdgeDictionary.items(): colorJoinedPieceDictionary[colorTuple] = [] for assortedEdgeDictionary in pieceList: colorJoinedPieceDictionary[colorTuple].append(GetJoinedEdgeList(assortedEdgeDictionary, keepEveryPoint)) stringIO = io.StringIO() stringIO.write(GetSVGHeader(*image.size)) for colorTuple, shapeList in colorJoinedPieceDictionary.items(): for shape in shapeList: stringIO.write(""" <path d=" """) for subsidaryShape in shape: pointTuple = subsidaryShape.pop(0)[0] stringIO.write(""" M %d,%d """ % pointTuple) for edgeTuple in subsidaryShape: pointTuple = edgeTuple[0] stringIO.write(""" L %d,%d """ % pointTuple) stringIO.write(""" Z """) stringIO.write(""" " style="fill:rgb%s; fill-opacity:%.3f; stroke:none;" />\n""" % (colorTuple[0:3], float(colorTuple[3]) / 255)) stringIO.write("""</svg>\n""") return stringIO.getvalue() ################################################################################ # SVG 데이터 구하기 2 ################################################################################ def GetSVGData2(image, opaque = None): stringIO = io.StringIO() stringIO.write(GetSVGHeader(*image.size)) width, height = image.size for x in range(width): for y in range(height): pointTuple = (x, y) colorTuple = image.getpixel(pointTuple) if opaque and not colorTuple[3]: continue stringIO.write(""" <rect x="%d" y="%d" width="1" height="1" style="fill:rgb%s; fill-opacity:%.3f; stroke:none;" />\n"""\ % (x, y, colorTuple[0:3], float(colorTuple[3]) / 255)) stringIO.write("""</svg>\n""") return stringIO.getvalue() ################################################################################ # SVG 파일 생성하기 ################################################################################ def CreateSVGFile(pngFilePath, contiguous = None, opaque = None, keepEveryPoint = None): try: pngImageFile = Image.open(pngFilePath) except IOError: print("이미지 파일을 열 수가 없습니다 : %s\n" % pngFilePath) sys.exit(1) image = pngImageFile.convert("RGBA") if contiguous: return GetSVGData1(image, opaque, keepEveryPoint) else: return GetSVGData2(image, opaque) ################################################################################ # 프로그램 시작하기 ################################################################################ logging.basicConfig() log = logging.getLogger('png2svg') if __name__ == "__main__": parser = optparse.OptionParser() parser.add_option(\ "-v", "--verbose", action = "store_true", dest = "verbosity", help = "Print verbose information for debugging", default = None) parser.add_option(\ "-q", "--quiet", action = "store_false", dest = "verbosity", help = "Suppress warnings", default = None) parser.add_option(\ "-p", "--pixels", action = "store_false", dest = "contiguous", help = "Generate a separate shape for each pixel; do not group pixels into contiguous areas of the same colour", default = True) parser.add_option(\ "-o", "--opaque", action = "store_true", dest = "opaque", help = "Opaque only; do not create shapes for fully transparent pixels.", default = None) parser.add_option(\ "-1", "--one", action = "store_true", dest = "keeEveryPoint", help = "1-pixel-width edges on contiguous shapes; default is to remove intermediate points on straight line edges.", default = None) (options, argumentList) = parser.parse_args() if options.verbosity == True: log.setLevel(logging.DEBUG) elif options.verbosity == False: log.setLevel(logging.ERROR) print(CreateSVGFile(argumentList[0], contiguous = options.contiguous, opaque = options.opaque, keepEveryPoint = options.keeEveryPoint)) |
※ 명령 프롬프트에서 env 가상 환경을 활성화하고 아래와 같이 실행하거나 ▶
■ BitmapImage 클래스를 사용해 WINFORM Bitmap 객체에서 비트맵 이미지를 구하는 방법을 보여준다. ▶ MainWindow.xaml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<Window x:Class="TestProject.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Width="800" Height="600" Title="TestProject" FontFamily="나눔고딕코딩" FontSize="16"> <Image Name="image" Margin="10" Stretch="UniformToFill" /> </Window> |
▶ MainWindow.xaml.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 |
using System; using System.IO; using System.Windows; using System.Windows.Media.Imaging; namespace TestProject; /// <summary> /// 메인 윈도우 /// </summary> public partial class MainWindow : Window { //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - MainWindow() /// <summary> /// 생성자 /// </summary> public MainWindow() { InitializeComponent(); System.Drawing.Image sourceImage = System.Drawing.Image.FromFile("IMAGE/sample.png"); BitmapSource bitmapSource = GetBitmapSource(sourceImage); this.image.Source = bitmapSource; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Private #region 비트맵 소스 구하기 - GetBitmapSource(sourceImage) /// <summary> /// 비트맵 소스 구하기 /// </summary> /// <param name="sourceImage">소스 이미지</param> /// <returns>비트맵 소스</returns> private BitmapSource GetBitmapSource(System.Drawing.Image sourceImage) { MemoryStream stream = new MemoryStream(); BitmapSource bitmapSource = null; try { string guid = sourceImage.RawFormat.Guid.ToString("B").ToUpper(); switch(guid) { case "{B96B3CAA-0728-11D3-9D7B-0000F81EF32E}" : // MemoryBMP case "{B96B3CAB-0728-11D3-9D7B-0000F81EF32E}" : // BMP sourceImage.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp); stream.Position = 0; BmpBitmapDecoder bmpBitmapDecoder = new BmpBitmapDecoder(stream, BitmapCreateOptions.None, BitmapCacheOption.Default); bitmapSource = bmpBitmapDecoder.Frames[0]; break; case "{B96B3CAF-0728-11D3-9D7B-0000F81EF32E}": // PNG sourceImage.Save(stream, System.Drawing.Imaging.ImageFormat.Png); stream.Position = 0; PngBitmapDecoder pngBitmapDecoder = new PngBitmapDecoder(stream, BitmapCreateOptions.None, BitmapCacheOption.Default); bitmapSource = pngBitmapDecoder.Frames[0]; break; case "{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}" : // JPEG sourceImage.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg); JpegBitmapDecoder jpegBitmapDecoder = new JpegBitmapDecoder(stream, BitmapCreateOptions.None, BitmapCacheOption.Default); stream.Position = 0; bitmapSource = jpegBitmapDecoder.Frames[0]; break; case "{B96B3CB0-0728-11D3-9D7B-0000F81EF32E}" : // GIF sourceImage.Save(stream, System.Drawing.Imaging.ImageFormat.Gif); GifBitmapDecoder gifBitmapDecoder = new GifBitmapDecoder(stream, BitmapCreateOptions.None, BitmapCacheOption.Default); stream.Position = 0; bitmapSource = gifBitmapDecoder.Frames[0]; break; case "{B96B3CB1-0728-11D3-9D7B-0000F81EF32E}" : // TIFF sourceImage.Save(stream, System.Drawing.Imaging.ImageFormat.Tiff); TiffBitmapDecoder tiffBitmapDecoder = new TiffBitmapDecoder(stream, BitmapCreateOptions.None, BitmapCacheOption.Default); stream.Position = 0; bitmapSource = tiffBitmapDecoder.Frames[0]; break; case "{B96B3CB5-0728-11D3-9D7B-0000F81EF32E}" : // ICON sourceImage.Save(stream, System.Drawing.Imaging.ImageFormat.Icon); IconBitmapDecoder iconBitmapDecoder = new IconBitmapDecoder(stream, BitmapCreateOptions.None, BitmapCacheOption.Default); stream.Position = 0; bitmapSource = iconBitmapDecoder.Frames[0]; break; case "{B96B3CAC-0728-11D3-9D7B-0000F81EF32E}" : // EMF case "{B96B3CAD-0728-11D3-9D7B-0000F81EF32E}" : // WMF case "{B96B3CB2-0728-11D3-9D7B-0000F81EF32E}" : // EXIF case "{B96B3CB3-0728-11D3-9D7B-0000F81EF32E}" : // PhotoCD case "{B96B3CB4-0728-11D3-9D7B-0000F81EF32E}" : // FlashPIX default : throw new InvalidOperationException("Unsupported image format."); } } catch { } return bitmapSource; } #endregion } |
TestProject.zip
■ Image 클래스를 사용해 움직이는 GIF 이미지를 만드는 방법을 보여준다. ▶ GIFImage.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 |
using System; using System.Windows.Media.Imaging; using System.Windows; using System.Windows.Controls; namespace TestProject; /// <summary> /// GIF 이미지 /// </summary> public class GIFImage : Image { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 디코더 /// </summary> private BitmapDecoder decoder = null; /// <summary> /// 타이머 /// </summary> private System.Timers.Timer timer = new System.Timers.Timer(); /// <summary> /// 타이머 잠금 /// </summary> private object timerLock = new object(); /// <summary> /// 프레임 카운트 /// </summary> private int frameCount = 0; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 타이머 주기 - Interval /// <summary> /// 타이머 주기 /// </summary> public double Interval { get { return this.timer.Interval; } set { this.timer.Interval = value; } } #endregion #region 재생 여부 - IsPlaying /// <summary> /// 재생 여부 /// </summary> public bool IsPlaying { get; private set; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - GIFImage() /// <summary> /// 생성자 /// </summary> public GIFImage() : base() { IsPlaying = false; Interval = 100; this.timer.Elapsed += timer_Elapsed; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region 시작하기 - Start() /// <summary> /// 시작하기 /// </summary> public void Start() { lock(this.timerLock) { if(this.decoder != null && this.decoder.Frames.Count > 1) { if(IsPlaying == false) { IsPlaying = true; this.timer.Start(); } } } } #endregion #region 중단하기 - Stop() /// <summary> /// 중단하기 /// </summary> public void Stop() { lock(this.timerLock) { IsPlaying = false; this.timer.Stop(); } } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Protected #region 속성 변경시 처리하기 - OnPropertyChanged(e) /// <summary> /// 속성 변경시 처리하기 /// </summary> /// <param name="e">이벤트 인자</param> protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e) { if(e.Property.Name == "Source") { if(e.NewValue != null && (e.OldValue == null || (e.NewValue.ToString() != e.OldValue.ToString()))) { Stop(); try { GifBitmapDecoder decoder = new GifBitmapDecoder(new Uri(e.NewValue.ToString()), BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.None); this.decoder = decoder; } catch { } Start(); } } base.OnPropertyChanged(e); } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Private #region 타이머 경과시 처리하기 - timer_Elapsed(sender, e) /// <summary> /// 타이머 경과시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { Dispatcher.BeginInvoke ( new Action ( delegate { this.frameCount = ++this.frameCount % this.decoder.Frames.Count; Source = this.decoder.Frames[this.frameCount]; InvalidateArrange(); } ), null ); } #endregion } |
▶ MainWindow.xaml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
<Window x:Class="TestProject.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:TestProject" Width="800" Height="600" Title="TestProject" FontFamily="나눔고딕코딩" FontSize="16"> <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center"> <local:GIFImage HorizontalAlignment="Center" SnapsToDevicePixels="True" UseLayoutRounding="True" RenderOptions.BitmapScalingMode="NearestNeighbor" Stretch="None" Interval="100" Source="pack://application:,,,/IMAGE/elephant.gif" /> </StackPanel> </Window> |
TestProject.zip
■ DrawingView 클래스의 GetImageStream 메소드를 사용해 이미지를 구하는 방법을 보여준다. ▶ MainPage.xaml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<?xml version="1.0" encoding="utf-8" ?> <ContentPage x:Class="TestProject.MainPage" xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:toolkit="http://schemas.microsoft.com/dotnet/2022/maui/toolkit"> <Grid Margin="10" RowDefinitions="*,Auto,*"> <toolkit:DrawingView x:Name="drawingView" Grid.Row="0" Margin="10" Background="Beige" IsMultiLineModeEnabled="true" ShouldClearOnFinish="false" LineWidth="5" LineColor="Blue" /> <Button x:Name="captureButton" Grid.Row="1" Margin="10" Text="이미지 캡처" /> <Image x:Name="image" Grid.Row="2" /> </Grid> </ContentPage> |
▶ MainPage.xaml.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
using System.Collections.ObjectModel; using CommunityToolkit.Maui.Core; namespace TestProject; /// <summary> /// 메인 페이지 /// </summary> public partial class MainPage : ContentPage { //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - MainPage() /// <summary> /// 생성자 /// </summary> public MainPage() { InitializeComponent(); this.drawingView.Lines = new ObservableCollection<IDrawingLine>(); this.captureButton.Clicked += captureButton_Clicked; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Private #region 이미지 캡처 버튼 클릭시 처리하기 - captureButton_Clicked(sender, e) /// <summary> /// 이미지 캡처 버튼 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private async void captureButton_Clicked(object sender, EventArgs e) { Stream stream = await drawingView.GetImageStream(this.image.Width, this.image.Height); this.image.Source = ImageSource.FromStream(() => stream); } #endregion } |
▶ MauiProgram.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
using CommunityToolkit.Maui; namespace TestProject; /// <summary> /// MAUI 프로그램 /// </summary> public static class MauiProgram { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Public #region MAUI 앱 생성하기 - CreateMauiApp() /// <summary> /// MAUI 앱 생성하기 /// </summary> /// <returns>MAUI 앱</returns> public static MauiApp CreateMauiApp() { MauiAppBuilder builder = MauiApp.CreateBuilder(); builder .UseMauiApp<App>() .UseMauiCommunityToolkit() .ConfigureFonts ( fontCollection => { fontCollection.AddFont("OpenSans-Regular.ttf" , "OpenSansRegular" ); fontCollection.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold"); } ); return builder.Build(); } #endregion } |
TestProject.zip
■ ImageResourceConverter 클래스에서 포함 리소스 이미지 → ImageResource 변환자를 사용하는 방법을 보여준다. ▶ MainPage.xaml
1 2 3 4 5 6 7 8 9 10 11 |
<?xml version="1.0" encoding="utf-8" ?> <ContentPage x:Class="TestProject.MainPage" xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"> <Image x:Name="image" HorizontalOptions="Center" VerticalOptions="Center" WidthRequest="300" /> </ContentPage> |
▶ MainPage.xaml.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
using CommunityToolkit.Maui.Converters; namespace TestProject; /// <summary> /// 메인 페이지 /// </summary> public partial class MainPage : ContentPage { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 선택 값 - SelectedValue /// <summary> /// 선택 값 /// </summary> public string SelectedValue { get; set; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - MainPage() /// <summary> /// 생성자 /// </summary> public MainPage() { InitializeComponent(); SelectedValue = "TestProject.IMAGE.sample.png"; ImageResourceConverter converter = new ImageResourceConverter(); this.image.SetBinding ( Image.SourceProperty, new Binding("SelectedValue", converter : converter) ); BindingContext = this; } #endregion } |
▶ MauiProgram.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
using CommunityToolkit.Maui; namespace TestProject; /// <summary> /// MAUI 프로그램 /// </summary> public static class MauiProgram { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Public #region MAUI 앱 생성하기 - CreateMauiApp() /// <summary> /// MAUI 앱 생성하기 /// </summary> /// <returns>MAUI 앱</returns> public static MauiApp CreateMauiApp() { MauiAppBuilder builder = MauiApp.CreateBuilder(); builder .UseMauiApp<App>() .UseMauiCommunityToolkit() .ConfigureFonts ( fontCollection => { fontCollection.AddFont("OpenSans-Regular.ttf" , "OpenSansRegular" ); fontCollection.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold"); } ); return builder.Build(); } #endregion } |
TestProject.zip
■ ImageResourceConverter 엘리먼트에서 포함 리소스 이미지 → ImageResource 변환자를 사용하는 방법을 보여준다. ▶ MainPage.xaml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<?xml version="1.0" encoding="utf-8" ?> <ContentPage x:Class="TestProject.MainPage" xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:toolkit="http://schemas.microsoft.com/dotnet/2022/maui/toolkit"> <ContentPage.Resources> <toolkit:ImageResourceConverter x:Key="ImageResourceConverterKey" /> </ContentPage.Resources> <Image HorizontalOptions="Center" VerticalOptions="Center" WidthRequest="300" Source="{Binding SelectedValue, Converter={StaticResource ImageResourceConverterKey}}" /> </ContentPage> |
▶ MainPage.xaml.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
namespace TestProject; /// <summary> /// 메인 페이지 /// </summary> public partial class MainPage : ContentPage { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 선택 값 - SelectedValue /// <summary> /// 선택 값 /// </summary> public string SelectedValue { get; set; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - MainPage() /// <summary> /// 생성자 /// </summary> public MainPage() { InitializeComponent(); SelectedValue = "TestProject.IMAGE.sample.png"; BindingContext = this; } #endregion } |
▶ MauiProgram.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
using CommunityToolkit.Maui; namespace TestProject; /// <summary> /// MAUI 프로그램 /// </summary> public static class MauiProgram { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Public #region MAUI 앱 생성하기 - CreateMauiApp() /// <summary> /// MAUI 앱 생성하기 /// </summary> /// <returns>MAUI 앱</returns> public static MauiApp CreateMauiApp() { MauiAppBuilder builder = MauiApp.CreateBuilder(); builder .UseMauiApp<App>() .UseMauiCommunityToolkit() .ConfigureFonts ( fontCollection => { fontCollection.AddFont("OpenSans-Regular.ttf" , "OpenSansRegular" ); fontCollection.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold"); } ); return builder.Build(); } #endregion } |
TestProject.zip
■ ByteArrayToImageSourceConverter 클래스에서 바이트 배열 ↔ 이미지 소스 변환자를 사용하는 방법을 보여준다. ▶ MainPage.xaml
1 2 3 4 5 6 7 8 9 10 11 |
<?xml version="1.0" encoding="utf-8" ?> <ContentPage x:Class="TestProject.MainPage" xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"> <Image x:Name="image" HorizontalOptions="Center" VerticalOptions="Center" WidthRequest="300" /> </ContentPage> |
▶ MainPage.xaml.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
using CommunityToolkit.Maui.Converters; namespace TestProject; /// <summary> /// 메인 페이지 /// </summary> public partial class MainPage : ContentPage { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 이미지 바이트 배열 - ImageByteArray /// <summary> /// 이미지 바이트 배열 /// </summary> public byte[] ImageByteArray { get; set; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - MainPage() /// <summary> /// 생성자 /// </summary> public MainPage() { InitializeComponent(); ByteArrayToImageSourceConverter converter = new ByteArrayToImageSourceConverter(); this.image.SetBinding ( Image.SourceProperty, new Binding("ImageByteArray", converter : converter) ); using Stream sourceStream = FileSystem.Current.OpenAppPackageFileAsync("sample.png").Result; using MemoryStream targetStream = new MemoryStream(); sourceStream.CopyTo(targetStream); ImageByteArray = targetStream.ToArray(); BindingContext = this; } #endregion } |
▶ MauiProgram.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
using CommunityToolkit.Maui; namespace TestProject; /// <summary> /// MAUI 프로그램 /// </summary> public static class MauiProgram { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Public #region MAUI 앱 생성하기 - CreateMauiApp() /// <summary> /// MAUI 앱 생성하기 /// </summary> /// <returns>MAUI 앱</returns> public static MauiApp CreateMauiApp() { MauiAppBuilder builder = MauiApp.CreateBuilder(); builder .UseMauiApp<App>() .UseMauiCommunityToolkit() .ConfigureFonts ( fontCollection => { fontCollection.AddFont("OpenSans-Regular.ttf" , "OpenSansRegular" ); fontCollection.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold"); } ); return builder.Build(); } #endregion } |
TestProject.zip
■ ByteArrayToImageSourceConverter 엘리먼트에서 바이트 배열 ↔ 이미지 소스 변환자를 사용하는 방법을 보여준다. ▶ MainPage.xaml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<?xml version="1.0" encoding="utf-8" ?> <ContentPage x:Class="TestProject.MainPage" xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:toolkit="http://schemas.microsoft.com/dotnet/2022/maui/toolkit"> <ContentPage.Resources> <toolkit:ByteArrayToImageSourceConverter x:Key="ByteArrayToImageSourceConverterKey" /> </ContentPage.Resources> <Image HorizontalOptions="Center" VerticalOptions="Center" WidthRequest="300" Source="{Binding ImageByteArray, Mode=OneWay, Converter={StaticResource ByteArrayToImageSourceConverterKey}}" /> </ContentPage> |
▶ MainPage.xaml.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
namespace TestProject; /// <summary> /// 메인 페이지 /// </summary> public partial class MainPage : ContentPage { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 이미지 바이트 배열 - ImageByteArray /// <summary> /// 이미지 바이트 배열 /// </summary> public byte[] ImageByteArray { get; set; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - MainPage() /// <summary> /// 생성자 /// </summary> public MainPage() { InitializeComponent(); using Stream sourceStream = FileSystem.Current.OpenAppPackageFileAsync("sample.png").Result; using MemoryStream targetStream = new MemoryStream(); sourceStream.CopyTo(targetStream); ImageByteArray = targetStream.ToArray(); BindingContext = this; } #endregion } |
▶ MauiProgram.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
using CommunityToolkit.Maui; namespace TestProject; /// <summary> /// MAUI 프로그램 /// </summary> public static class MauiProgram { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Public #region MAUI 앱 생성하기 - CreateMauiApp() /// <summary> /// MAUI 앱 생성하기 /// </summary> /// <returns>MAUI 앱</returns> public static MauiApp CreateMauiApp() { MauiAppBuilder builder = MauiApp.CreateBuilder(); builder .UseMauiApp<App>() .UseMauiCommunityToolkit() .ConfigureFonts ( fontCollection => { fontCollection.AddFont("OpenSans-Regular.ttf" , "OpenSansRegular" ); fontCollection.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold"); } ); return builder.Build(); } #endregion } |
TestProject.zip
■ 고품질 이미지 크기를 변경하는 방법을 보여준다. ▶ ImageHelper.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 |
using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; namespace TestProject { /// <summary> /// 이미지 헬퍼 /// </summary> public static class ImageHelper { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 이미지 코덱 정보 딕셔너리 /// </summary> private static Dictionary<string, ImageCodecInfo> _imageCodecInfoDictionary = null; /// <summary> /// 이미지 코텍 정보 딕셔너리 잠금 /// </summary> private static object _imageCodecInfoDictionaryLock = new object(); #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Public #region 이미지 코덱 정보 딕셔너리 - ImageCodecInfoDictionary /// <summary> /// 이미지 코덱 정보 딕셔너리 /// </summary> public static Dictionary<string, ImageCodecInfo> ImageCodecInfoDictionary { get { if(_imageCodecInfoDictionary == null) { lock(_imageCodecInfoDictionaryLock) { if(_imageCodecInfoDictionary == null) { _imageCodecInfoDictionary = new Dictionary<string, ImageCodecInfo>(); foreach(ImageCodecInfo codecInfo in ImageCodecInfo.GetImageEncoders()) { _imageCodecInfoDictionary.Add(codecInfo.MimeType.ToLower(), codecInfo); } } } } return _imageCodecInfoDictionary; } } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Public #region 이미지 크기 변경하기 - ResizeImage(sourceImage, width, height) /// <summary> /// 이미지 크기 변경하기 /// </summary> /// <param name="sourceImage">소스 이미지</param> /// <param name="width">너비</param> /// <param name="height">높이</param> /// <returns>이미지</returns> public static Bitmap ResizeImage(Image sourceImage, int width, int height) { Bitmap targetBitmap = new Bitmap(width, height); targetBitmap.SetResolution(sourceImage.HorizontalResolution, sourceImage.VerticalResolution); using(Graphics graphics = Graphics.FromImage(targetBitmap)) { graphics.CompositingQuality = CompositingQuality.HighQuality; graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; graphics.SmoothingMode = SmoothingMode.HighQuality; graphics.DrawImage(sourceImage, 0, 0, targetBitmap.Width, targetBitmap.Height); } return targetBitmap; } #endregion #region 이미지 코덱 정보 구하기 - GetImageCodecInfo(mimeType) /// <summary> /// 이미지 코덱 정보 구하기 /// </summary> /// <param name="mimeType">MIME 타입</param> /// <returns>이미지 코텍 정보</returns> public static ImageCodecInfo GetImageCodecInfo(string mimeType) { string lookupKey = mimeType.ToLower(); ImageCodecInfo codecInfo = null; if(ImageCodecInfoDictionary.ContainsKey(lookupKey)) { codecInfo = ImageCodecInfoDictionary[lookupKey]; } return codecInfo; } #endregion #region JPEG 저장하기 - SaveJPEG(filePath, sourceImage, quality) /// <summary> /// JPEG 저장하기 /// </summary> /// <param name="filePath">파일 경로</param> /// <param name="sourceImage">소스 이미지</param> /// <param name="quality">품질</param> public static void SaveJPEG(string filePath, Image sourceImage, int quality) { if((quality < 0) || (quality > 100)) { string error = string.Format ( "Jpeg image quality must be between 0 and 100, with 100 being the highest quality. A value of {0} was specified.", quality ); throw new ArgumentOutOfRangeException(error); } EncoderParameter parameter = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality); ImageCodecInfo codecInfo = GetImageCodecInfo("image/jpeg"); EncoderParameters parameters = new EncoderParameters(1); parameters.Param[0] = parameter; sourceImage.Save(filePath, codecInfo, parameters); } #endregion } } |
▶ MainForm.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
using System; using System.Drawing; using System.Windows.Forms; namespace TestProject { /// <summary> /// 메인 폼 /// </summary> public partial class MainForm : Form { //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - MainForm() /// <summary> /// 생성자 /// </summary> public MainForm() { InitializeComponent(); this.sourcePictureBox.Image = Properties.Resources.source; this.sourcePictureBox.Size = Properties.Resources.source.Size; this.resizeButton.Click += resizeButton_Click; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Private #region 이미지 크기 변경하기 버튼 클릭시 처리하기 - resizeButton_Click(sender, e) /// <summary> /// 이미지 크기 변경하기 버튼 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void resizeButton_Click(object sender, EventArgs e) { if(this.targetPictureBox.Image == null) { int targetWidth = 300; double factor = (double)targetWidth / this.sourcePictureBox.Image.Width; int targetHeight = (int)(this.sourcePictureBox.Image.Height * factor); Image targetImage = ImageHelper.ResizeImage(this.sourcePictureBox.Image, targetWidth, targetHeight); this.targetPictureBox.Image = targetImage; this.targetPictureBox.Size = targetImage.Size; } } #endregion } } |
TestProject.zip
■ 프로젝트 파일에서 스플래시 화면을 추가하는 방법을 보여준다. ▶ 예제 코드 (XML)
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<ItemGroup> <MauiSplashScreen Include="Resources\Images\splashscreen.svg" /> </ItemGroup> 또는 <ItemGroup> <MauiSplashScreen Include="Resources\appiconfg.svg" Color="#512bd4" BaseSize="128,128" /> </ItemGroup> |
■ 프로젝트 파일에 앱 아이콘을 추가하는 방법을 보여준다. ▶ 예제 코드 (XML)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<ItemGroup> <MauiIcon Include="Resources\Images\appicon.png" /> </ItemGroup> 또는 <ItemGroup> <MauiIcon Include="Resources\appicon.svg" ForegroundFile="Resources\appiconfg.svg" Color="#512bd4" /> </ItemGroup> |
■ 프로젝트 파일에 이미지 파일을 추가하는 방법을 보여준다. ▶ 예제 코드 (XML)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<ItemGroup> <MauiImage Include="Resources\Images\**\*" /> </ItemGroup> 또는 <ItemGroup> <MauiImage Include="Resources\Images\*" /> <MauiImage Update="Resources\Images\dotnet_bot.svg" BaseSize="168,208" /> </ItemGroup> |
■ Shadow 엘리먼트를 사용해 클리핑 이미지 그림자를 설정하는 방법을 보여준다. ▶ MainPage.xaml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
<?xml version="1.0" encoding="utf-8" ?> <ContentPage x:Class="TestProject.MainPage" xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"> <Image HorizontalOptions="Center" VerticalOptions="Center" WidthRequest="220" HeightRequest="220" Aspect="AspectFill" Source="https://aka.ms/campus.jpg"> <Image.Clip> <EllipseGeometry Center="220,250" RadiusX="220" RadiusY="220" /> </Image.Clip> <Image.Shadow> <Shadow Offset="10,10" Opacity="0.8" Brush="Black" /> </Image.Shadow> </Image> </ContentPage> |
※ 프리뷰 버전 테스트시, 클리핑 영역을 설정하면 그림자가 정상적으로
■ Shadow 엘리먼트를 사용해 이미지 그림자를 설정하는 방법을 보여준다. ▶ MainPage.xaml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<?xml version="1.0" encoding="utf-8" ?> <ContentPage x:Class="TestProject.MainPage" xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"> <Image HorizontalOptions="Center" VerticalOptions="Center" WidthRequest="250" HeightRequest="310" Source="dotnet_bot.png"> <Image.Shadow> <Shadow Offset="20,20" Radius="40" Opacity="0.8" Brush="Black" /> </Image.Shadow> </Image> </ContentPage> |
TestProject.zip
■ PlatformImage 클래스의 FromStream 정적 메소드를 이용해 어셈블리 포함 리소스 이미지를 구하는 방법을 보여준다. ▶ PlatformImage 클래스 : FromStream 정적 메소드를 이용해
■ ICanvas 인터페이스의 DrawImage 메소드를 사용해 이미지를 그리는 방법을 보여준다. ▶ GraphicsDrawable.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
using System.Reflection; using Microsoft.Maui.Graphics.Platform; namespace TestProject; /// <summary> /// 그래픽스 그리기 가능형 /// </summary> public class GraphicsDrawable : IDrawable { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region 그리기 - Draw(canvas, dirtyRectangle) /// <summary> /// 그리기 /// </summary> /// <param name="canvas">캔버스</param> /// <param name="dirtyRectangle">더티 사각형</param> public void Draw(ICanvas canvas, RectF dirtyRectangle) { canvas.FillColor = Colors.Yellow; canvas.FillRectangle(dirtyRectangle); Assembly assembly = GetType().GetTypeInfo().Assembly; using(Stream stream = assembly.GetManifestResourceStream("TestProject.IMAGE.sample.jpg")) { Microsoft.Maui.Graphics.IImage image = PlatformImage.FromStream(stream); float width; float height; float offset; if(image.Width > image.Height) { width = 250; height = 250 * image.Height / image.Width; offset = (width - height) / 2; canvas.DrawImage(image, 50, 50 + offset, width, height); } else { height = 250; width = 250 * image.Width / image.Height; offset = height - width; canvas.DrawImage(image, 50 + offset, 50, width, height); } } } #endregion } |
▶ MainPage.xaml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<?xml version="1.0" encoding="utf-8" ?> <ContentPage x:Class="TestProject.MainPage" xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:local="clr-namespace:TestProject"> <ContentPage.Resources> <local:GraphicsDrawable x:Key="GraphicsDrawableKey" /> </ContentPage.Resources> <GraphicsView HorizontalOptions="Center" VerticalOptions="Center" WidthRequest="350" HeightRequest="350" Drawable="{StaticResource GraphicsDrawableKey}" /> </ContentPage> |
TestProject.zip
■ FontImageSource 엘리먼트를 사용해 IONICONS 폰트 아이콘을 표시하는 방법을 보여준다. ▶ MauiProgram.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
namespace TestProject; /// <summary> /// MAUI 프로그램 /// </summary> public static class MauiProgram { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Public #region MAUI 앱 생성하기 - CreateMauiApp() /// <summary> /// MAUI 앱 생성하기 /// </summary> /// <returns>MAUI 앱</returns> public static MauiApp CreateMauiApp() { MauiAppBuilder builder = MauiApp.CreateBuilder(); builder .UseMauiApp<App>() .ConfigureFonts ( fontCollection => { fontCollection.AddFont("OpenSans-Regular.ttf" , "OpenSansRegular" ); fontCollection.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold"); fontCollection.AddFont("ionicons.ttf" , "ionicons" ); } ); return builder.Build(); } #endregion } |
▶ MainPage.xaml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
<?xml version="1.0" encoding="utf-8" ?> <ContentPage x:Class="TestProject.MainPage" xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"> <StackLayout HorizontalOptions="Center" VerticalOptions="Center" Orientation="Horizontal" Spacing="10"> <Image> <Image.Source> <FontImageSource FontFamily="ionicons" Size="48" Color="Red" Glyph="" /> </Image.Source> </Image> <Image> <Image.Source> <FontImageSource FontFamily="ionicons" Size="48" Color="Green" Glyph="" /> </Image.Source> </Image> <Image> <Image.Source> <FontImageSource FontFamily="ionicons" Size="48" Color="Blue" Glyph="" /> </Image.Source> </Image> </StackLayout> </ContentPage> |
TestProject.zip
■ IValueConverter 인터페이스를 구현해 이미지 URL→이미지 소스 변환자를 사용하는 방법을 보여준다. ▶ 예제 코드 (C#)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
using System.Globalization; /// <summary> /// 이미지 URL→이미지 소스 변환자 /// </summary> public class ImageSourceConverter : IValueConverter { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region 변환하기 - Convert(sourceValue, targetType, parameter, cultureInfo) /// <summary> /// 변환하기 /// </summary> /// <param name="sourceValue">소스 값</param> /// <param name="targetType">타겟 타입</param> /// <param name="parameter">매개 변수</param> /// <param name="cultureInfo">문화 정보</param> /// <returns>변환 값</returns> public object Convert(object sourceValue, Type targetType, object parameter, CultureInfo cultureInfo) { string imageURL = sourceValue as string; if(string.IsNullOrWhiteSpace(imageURL)) { return null; } return ImageSource.FromUri(new Uri(imageURL)); } #endregion #region 역변환하기 - ConvertBack(sourceValue, targetType, parameter, cultureInfo) /// <summary> /// 역변환하기 /// </summary> /// <param name="sourceValue">소스 값</param> /// <param name="targetType">타겟 타입</param> /// <param name="parameter">매개 변수</param> /// <param name="cultureInfo">문화 정보</param> /// <returns>역변환 값</returns> public object ConvertBack(object sourceValue, Type targetType, object parameter, CultureInfo cultureInfo) { throw new NotImplementedException(); } #endregion } |
■ FontImageSource 클래스를 사용해 IONICONS 폰트 아이콘을 표시하는 방법을 보여준다. ▶ FontModel.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
namespace TestProject; /// <summary> /// 폰트 모델 /// </summary> public class FontModel { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 아이콘 - Icon /// <summary> /// 아이콘 /// </summary> public ImageSource Icon { get; set; } #endregion #region 글리프 - Glyph /// <summary> /// 글리프 /// </summary> public string Glyph { get; set; } #endregion } |
▶ MainPage.xaml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
<?xml version="1.0" encoding="utf-8" ?> <ContentPage x:Class="TestProject.MainPage" xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:local="clr-namespace:TestProject"> <CollectionView x:Name="collectionView" Margin="10"> <CollectionView.ItemTemplate> <DataTemplate> <HorizontalStackLayout Margin="10"> <Image VerticalOptions="Center" WidthRequest="32" HeightRequest="32" Source="{Binding Icon}" /> <Label Margin="10,0,0,0" VerticalOptions="Center" Text="{Binding Glyph}" /> </HorizontalStackLayout> </DataTemplate> </CollectionView.ItemTemplate> </CollectionView> </ContentPage> |
▶ MainPage.xaml.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 |
using System.Globalization; using System.Text.RegularExpressions; namespace TestProject; /// <summary> /// 메인 페이지 /// </summary> public partial class MainPage : ContentPage { //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - MainPage() /// <summary> /// 생성자 /// </summary> public MainPage() { InitializeComponent(); List<FontModel> list = new List<FontModel>(); for(int i = 0xf0ff ; i < 0xf3aa; i++) { string escapedUnicode = "\\u" + i.ToString("x4"); string nonEscapedUnicode = GetNonEscapedUnicodeString(escapedUnicode); FontImageSource fontImageSource = new FontImageSource(); fontImageSource.Color = Colors.Blue; fontImageSource.FontFamily = "ionicons"; fontImageSource.Glyph = nonEscapedUnicode; list.Add(new FontModel { Icon = fontImageSource, Glyph = escapedUnicode }); } this.collectionView.ItemsSource = list; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Private #region 비 이스케이프 유니코드 문자열 구하기 - GetNonEscapedUnicodeString(sourceEscapedUnicodeString) /// <summary> /// 비 이스케이프 유니코드 문자열 구하기 /// </summary> /// <param name="sourceEscapedUnicodeString">소스 이스케이프 유니코드 문자열</param> /// <returns>비 이스케이프 유니코드 문자열</returns> private string GetNonEscapedUnicodeString(string sourceEscapedUnicodeString) { return Regex.Replace ( sourceEscapedUnicodeString, @"\\u(?<Value>[a-zA-Z0-9]{4})", m => { return ((char)int.Parse(m.Groups["Value"].Value, NumberStyles.HexNumber)).ToString(); } ); } #endregion } |
TestProject.zip
■ ImageButton 엘리먼트를 사용하는 방법을 보여준다. ▶ MainPage.xaml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<?xml version="1.0" encoding="utf-8" ?> <ContentPage x:Class="TestProject.MainPage" xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"> <StackLayout HorizontalOptions="Center" VerticalOptions="Center"> <ImageButton x:Name="imageButton" HorizontalOptions="Center" Source="dotnet_bot.png" /> <Label x:Name="label" HorizontalOptions="Center" Margin="0, 10, 0, 0" Text="클릭 수 : 0" /> </StackLayout> </ContentPage> |
▶ MainPage.xaml.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
namespace TestProject; /// <summary> /// 메인 페이지 /// </summary> public partial class MainPage : ContentPage { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 카운트 /// </summary> private int count; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - MainPage() /// <summary> /// 생성자 /// </summary> public MainPage() { InitializeComponent(); this.imageButton.Clicked += imageButton_Clicked; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Private #region 이미지 버튼 클릭시 처리하기 - imageButton_Clicked(sender, e) /// <summary> /// 이미지 버튼 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void imageButton_Clicked(object sender, EventArgs e) { this.count += 1; this.label.Text = $"클릭 수 : {this.count}"; } #endregion } |
TestProject.zip
■ Image 엘리먼트의 Clip 속성을 사용해 이미지를 클리핑하는 방법을 보여준다. ▶ 예제 코드 (XAML)
1 2 3 4 5 6 7 8 9 10 |
<Image Source="monkeyface.png"> <Image.Clip> <EllipseGeometry Center="180,180" RadiusX="100" RadiusY="100" /> </Image.Clip> </Image> |
■ Image 클래스의 IsAnimationPlaying 속성을 사용해 GIF 이미지 애니메이션을 만드는 방법을 보여준다. ▶ MainPage.xaml
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<?xml version="1.0" encoding="utf-8" ?> <ContentPage x:Class="TestProject.MainPage" xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"> <Image HorizontalOptions="Center" VerticalOptions="Center" WidthRequest="140" HeightRequest="60" Source="cheetah.gif" /> </ContentPage> |
▶ MainPage.xaml.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
namespace TestProject; /// <summary> /// 메인 페이지 /// </summary> public partial class MainPage : ContentPage { //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - MainPage() /// <summary> /// 생성자 /// </summary> public MainPage() { InitializeComponent(); Loaded += ContentPage_Loaded; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Private #region 컨텐트 페이지 로드시 처리하기 - ContentPage_Loaded(sender, e) /// <summary> /// 컨텐트 페이지 로드시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void ContentPage_Loaded(object sender, EventArgs e) { this.image.IsAnimationPlaying = true; } #endregion } |
TestProject.zip