简体   繁体   中英

Casting a RGB string to a Color type

I am reading from a file that has a list of RGB values, ie

0,1,6
0,2,6
0,43,170
0,42,168
0,44,175
0,44,176
0,44,176
0,221,255
0,222,255
0,222,255

I have stored all these values into a string[] array, with this constructor:

    public Program(int rows, String fileLocation) {

        int i;
        String line;
        count = 0;
        this.rows = rows;
        this.fileLocation = fileLocation;
        stringArray = new String[rows];

        try {
            System.IO.StreamReader file = new System.IO.StreamReader(fileLocation);
            for (i = 0; i < rows; i++) {
                while ((line = file.ReadLine()) != null) {
                    stringArray[i] = line;
                    count++;
                    break;
                }
            }
        }
        catch (Exception e) {
            throw (e);
        }
    }

I wanted to convert these current String s to Color values, as they are just RGB values in the form of Strings.

So I used this method:

    public Color[] convertToColorArray() {
        for (int i = 0; i < rows; i++) {
            colorArray[i] = System.Drawing.Color.FromArgb(stringArray[i]);
        }
        return colorArray;
    }

With that said, I am getting the following error:

在此处输入图片说明

Telling me I have an invalid arg. I understand that the argument is not necessarily something like this 255,255,255 which are three ints separated by commas, but my string input is in that format. What is it I should do? Should I cast it to something? Should I simply store those values into a Color[] in my constructor in the beginning?

look at the overloads for Color.FromArgb , they all expect int to be passed in. So no, you can't just pass in a string and expect it to work. However it is not hard to turn your string in to a set of ints.

public Color[] convertToColorArray() {
    for (int i = 0; i < rows; i++) {
        //This gives us an array of 3 strings each representing a number in text form.
        var splitString = stringArray[i].Split(','); 

        //converts the array of 3 strings in to an array of 3 ints.
        var splitInts = splitString.Select(item => int.Parse(item)).ToArray(); 

        //takes each element of the array of 3 and passes it in to the correct slot
        colorArray[i] = System.Drawing.Color.FromArgb(splitInts[0], splitInts[1], splitInts[2]); 
    }
    return colorArray;
}

This code all assumes your source file is well formed so that string.Split will always return at least 3 arrays and int.Parse will never fail at parsing the input.

The function you're trying to call takes 1-4 parameters

http://msdn.microsoft.com/en-us/library/system.drawing.color.fromargb%28v=vs.110%29.aspx

Assuming you're sure you have three values in each line - this should work

string[] splitArray = stringArray[i].Split(',');

System.Drawing.FromARGB(Int32.Parse(splitArray[0]),Int32.Parse(splitArray[1]),Int32.Parse(splitArray[2]);

You can write this cleaner if you convert the Array into an array of int[] beforehand

int[] intArray = splitArray.Select(sa => Int32.Parse(sa)).ToArray();

then you can just call intArray[0] et cetera.

Something like this?

var colors = File.ReadLines(fname)
    .Select(line => line.Split(','))
    .Select(p => Color.FromArgb(byte.Parse(p[0]), byte.Parse(p[1]), byte.Parse(p[2])))
    .ToList();

I use an extension method of string to handle without throws using transparent as fallback:

    private static System.Drawing.Color ToColor(this string color)
    {
        var arrColorFragments = color?.Split(',').Select(sFragment => { int.TryParse(sFragment, out int fragment); return fragment; }).ToArray();

        switch (arrColorFragments?.Length)
        {
            case 3:
                return System.Drawing.Color.FromArgb(arrColorFragments[0], arrColorFragments[1], arrColorFragments[2]);
            case 4:
                return System.Drawing.Color.FromArgb(arrColorFragments[0], arrColorFragments[1], arrColorFragments[2], arrColorFragments[3]);
            default:
                return System.Drawing.Color.Transparent;
        }
    }

Note that I'm using C# 7. Maybe you'll have to tweak for C# version that you are using.

您需要获取字符串,并用逗号定界符将其分割,然后为每个字符串最后将其转换为int,最后将其放入FromArgb方法中。

The FromArgb method expects a single ARGB Int32 value, not what you want. Try this instead:

var items = stringArray[i].Split(",").Select(k => int.Parse(k)).ToArray();
colorArray[i] = Color.FromArgb(items[0], items[1], items[2]);

FromArgb has an overloaded method that accepts 3 integers as parameters, one for R one for G and one for B.

Split your stringArray[i] into 3 integer parts(should be easy, bcoz they r separated by commas) and pass them to the method.

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM