programing

컬러 코드를 미디어로 변환하는 방법.빗질?

cafebook 2023. 4. 13. 21:08
반응형

컬러 코드를 미디어로 변환하는 방법.빗질?

색상으로 채우고 싶은 직사각형이 있어요.내가 글을 쓸 때Fill = "#FFFFFF90"에러가 표시됩니다.

형식 'string'을 암시적으로 'System'으로 변환할 수 없습니다.창문들.미디어.브러시

조언 좀 해주세요.

XAML 판독 시스템이 사용하는 것과 같은 메커니즘을 사용할 수 있습니다.유형 변환기

var converter = new System.Windows.Media.BrushConverter();
var brush = (Brush)converter.ConvertFromString("#FFFFFF90");
Fill = brush;

코드에서는 명시적으로 다음 명령어를 작성할 필요가 있습니다.Brush인스턴스:

Fill = new SolidColorBrush(Color.FromArgb(0xff, 0xff, 0x90))

WinRT(Windows Store App)의 경우

using Windows.UI;
using Windows.UI.Xaml.Media;

    public static Brush ColorToBrush(string color) // color = "#E7E44D"
    {
        color = color.Replace("#", "");
        if (color.Length == 6)
        {
            return new SolidColorBrush(ColorHelper.FromArgb(255,
                byte.Parse(color.Substring(0, 2), System.Globalization.NumberStyles.HexNumber),
                byte.Parse(color.Substring(2, 2), System.Globalization.NumberStyles.HexNumber),
                byte.Parse(color.Substring(4, 2), System.Globalization.NumberStyles.HexNumber)));
        }
        else
        {
            return null;
        }
    }

파티에 너무 늦어서 미안해!WinRT에서도 비슷한 문제가 발생했습니다.WPF와 WinRT 중 어느 쪽을 사용하고 있는지는 잘 모르겠습니다만, 몇 가지 점에서 다릅니다(다른 것에 비해 좋은 것도 있습니다).어떤 상황에 처하든 이것이 전반적인 사람들에게 도움이 되기를 바랍니다.

제가 만든 컨버터 클래스의 코드를 언제든지 사용하여 C# 코드 이면에서 재사용하고 실행할 수 있습니다.또, 사용하고 있는 장소에서도 사용할 수 있습니다.솔직히 다음과 같습니다.

6자리(RGB) 또는 8자리(ARGB)의 16진수 값을 사용할 수 있다는 취지에서 작성했습니다.

그래서 변환기 클래스를 만들었습니다.

public class StringToSolidColorBrushConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, string language)
    {
        var hexString = (value as string).Replace("#", "");

        if (string.IsNullOrWhiteSpace(hexString)) throw new FormatException();
        if (hexString.Length != 6 || hexString.Length != 8) throw new FormatException();

        try
        {
            var a = hexString.Length == 8 ? hexString.Substring(0, 2) : "255";
            var r = hexString.Length == 8 ? hexString.Substring(2, 2) : hexString.Substring(0, 2);
            var g = hexString.Length == 8 ? hexString.Substring(4, 2) : hexString.Substring(2, 2);
            var b = hexString.Length == 8 ? hexString.Substring(6, 2) : hexString.Substring(4, 2);

            return new SolidColorBrush(ColorHelper.FromArgb(
                byte.Parse(a, System.Globalization.NumberStyles.HexNumber),
                byte.Parse(r, System.Globalization.NumberStyles.HexNumber),
                byte.Parse(g, System.Globalization.NumberStyles.HexNumber),
                byte.Parse(b, System.Globalization.NumberStyles.HexNumber)));
        }
        catch
        {
            throw new FormatException();
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, string language)
    {
        throw new NotImplementedException();
    }
}

내 App.xaml에 추가:

<ResourceDictionary>
    ...
    <converters:StringToSolidColorBrushConverter x:Key="StringToSolidColorBrushConverter" />
    ...
</ResourceDictionary>

My View의 Xaml에서 사용:

<Grid>
    <Rectangle Fill="{Binding RectangleColour,
               Converter={StaticResource StringToSolidColorBrushConverter}}"
               Height="20" Width="20" />
</Grid>

주술이 통한다!

사이드 노트...유감스럽게도 WinRT는System.Windows.Media.BrushConverterH.B.가 제안했기 때문에 다른 방법이 필요했습니다.그렇지 않았다면, 저는 VM 속성을 만들고,SolidColorBrush(또는 이와 유사)부터RectangleColourstring 속성.

간단하게 확장 기능을 작성할 수 있습니다.

    public static SolidColorBrush ToSolidColorBrush(this string hex_code)
    {
        return (SolidColorBrush)new BrushConverter().ConvertFromString(hex_code);
    }

다음으로 사용하는 방법:-

 SolidColorBrush accentBlue = "#3CACDC".ToSolidColorBrush();

어떤 버전의 WPF를 사용하고 있습니까?3.5와 4.0을 모두 사용해 보았고, Fill="#FF0000"은 XAML의 a에서 정상적으로 동작합니다.다만, 동작하지 않는 경우는 다른 구문이 있습니다.다음은 두 가지 방법으로 테스트한 3.5 XAML입니다.자원을 사용하는 것이 더 나을 것이다.

<Window x:Class="WpfApplication2.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <Rectangle Height="100" HorizontalAlignment="Left" Margin="100,12,0,0" Name="rectangle1" Stroke="Black" VerticalAlignment="Top" Width="200" Fill="#FF00AE00" />
    <Rectangle Height="100" HorizontalAlignment="Left" Margin="100,132,0,0" Name="rectangle2" Stroke="Black" VerticalAlignment="Top" Width="200" >
        <Rectangle.Fill>
            <SolidColorBrush Color="#FF00AE00" />
        </Rectangle.Fill>
    </Rectangle>
</Grid>

언급URL : https://stackoverflow.com/questions/6808739/how-to-convert-color-code-into-media-brush

반응형