Благодаря mindriot, прекрасно работает и спасает жизнь.
Здесь это в C #
note : если по какой-то причине вы не можете использовать целочисленные типы (противint's) (которые будут Java Integer в Mono), я оставил код, который использует C # int, в комментариях везде, где это связано.Просто поменяйте местами закомментированный int-код для некомментированного целочисленного кода везде, где вы его видите.
Пришлось использовать Integer, чтобы можно было определить, нет ли совпадения при проверке словаря / карты (TryGetValue) суффиксов (вв этом случае он будет нулевым, если вместо него используются целые, то выходной параметр будет равен 0, что соответствует первой записи карты, что, очевидно, не работает. Жаль, что TryGetValue не возвращал отрицательное значение принет совпадений!?).
public class DimensionConverter
{
// -- Initialize dimension string to constant lookup.
//public static readonly Dictionary<string, int> dimensionConstantLookup = initDimensionConstantLookup();
public static readonly Dictionary<string, Integer> dimensionConstantLookup = initDimensionConstantLookup();
//private static Dictionary<string, int> initDimensionConstantLookup()
private static Dictionary<string, Integer> initDimensionConstantLookup()
{
//Dictionary<string, int> m = new Dictionary<string, int>();
Dictionary<string, Integer> m = new Dictionary<string, Integer>();
m.Add("px", (Integer)((int)ComplexUnitType.Px));
m.Add("dip", (Integer)((int)ComplexUnitType.Dip));
m.Add("dp", (Integer)((int)ComplexUnitType.Dip));
m.Add("sp", (Integer)((int)ComplexUnitType.Sp));
m.Add("pt", (Integer)((int)ComplexUnitType.Pt));
m.Add("in", (Integer)((int)ComplexUnitType.In));
m.Add("mm", (Integer)((int)ComplexUnitType.Mm));
/*m.Add("px", (int)ComplexUnitType.Px);
m.Add("dip", (int)ComplexUnitType.Dip);
m.Add("dp", (int)ComplexUnitType.Dip);
m.Add("sp", (int)ComplexUnitType.Sp);
m.Add("pt", (int)ComplexUnitType.Pt);
m.Add("in", (int)ComplexUnitType.In);
m.Add("mm", (int)ComplexUnitType.Mm);*/
return m;
}
// -- Initialize pattern for dimension string.
private static Regex DIMENSION_PATTERN = new Regex("^\\s*(\\d+(\\.\\d+)*)\\s*([a-zA-Z]+)\\s*$");
public static int stringToDimensionPixelSize(string dimension, DisplayMetrics metrics)
{
// -- Mimics TypedValue.complexToDimensionPixelSize(int data, DisplayMetrics metrics).
InternalDimension internalDimension = stringToInternalDimension(dimension);
float value = internalDimension.value;
//float f = TypedValue.ApplyDimension((ComplexUnitType)internalDimension.unit, value, metrics);
float f = TypedValue.ApplyDimension((ComplexUnitType)(int)internalDimension.unit, value, metrics);
int res = (int)(f + 0.5f);
if (res != 0) return res;
if (value == 0) return 0;
if (value > 0) return 1;
return -1;
}
public static float stringToDimension(String dimension, DisplayMetrics metrics)
{
// -- Mimics TypedValue.complexToDimension(int data, DisplayMetrics metrics).
InternalDimension internalDimension = stringToInternalDimension(dimension);
//return TypedValue.ApplyDimension((ComplexUnitType)internalDimension.unit, internalDimension.value, metrics);
return TypedValue.ApplyDimension((ComplexUnitType)(int)internalDimension.unit, internalDimension.value, metrics);
}
private static InternalDimension stringToInternalDimension(String dimension)
{
// -- Match target against pattern.
MatchCollection matches = DIMENSION_PATTERN.Matches(dimension);
if (matches.Count > 0)
{
Match matcher = matches[0];
// -- Match found.
// -- Extract value.
float value = Float.ValueOf(matcher.Groups[1].Value).FloatValue();
// -- Extract dimension units.
string unit = matcher.Groups[3].ToString().ToLower();
// -- Get Android dimension constant.
//int dimensionUnit;
Integer dimensionUnit;
dimensionConstantLookup.TryGetValue(unit, out dimensionUnit);
//if (dimensionUnit == ????)
if (dimensionUnit == null)
{
// -- Invalid format.
throw new NumberFormatException();
}
else
{
// -- Return valid dimension.
return new InternalDimension(value, dimensionUnit);
}
}
else
{
// -- Invalid format.
throw new NumberFormatException();
}
}
private class InternalDimension
{
public float value;
//public int unit;
public Integer unit;
//public InternalDimension(float value, int unit)
public InternalDimension(float value, Integer unit)
{
this.value = value;
this.unit = unit;
}
}
}