2011-06-03 74 views
0

Renderscript中是否有字符串函數?像vsprintf,例如?Android Renderscript字符串函數?

具體而言,我想將一個浮點數轉換爲一個字符串。我是否必須從頭開始編寫?

謝謝!

+0

我寫了它從零開始... – Cubby 2011-06-08 23:39:27

回答

1

找不到一個簡單的方法,所以......

void drawInteger(int value, int x, int y) { 

    char text[50] = "0"; 
    int index = 0; 

    if(value != 0) { 

     index = 49; 
     text[index] = 0; 

     while(value > 0) { 

      index--; 

      int digitValue = value % 10; 

      text[index] = '0' + digitValue; 

      value /= 10; 
     } 

     if(value < 0) { 
      text[index--] = '-'; 
     }  
    } 

    rsgDrawText(&text[index], x - 10, y + 5); 
} 

void drawFloat(float value, int x, int y) { 

    char text[50] = "0.000"; 
    int index = 0; 

    if(value != 0) { 

     int integerPart = (int)(value * 1000); 

     index = 49; 
     text[index] = 0; 

     while(integerPart > 0) { 

      index--; 

      if(index == 45) { 
       text[index--] = '.'; 
      } 

      int digitValue = integerPart % 10; 

      text[index] = '0' + digitValue; 

      integerPart /= 10; 
     } 

     if(value < 0) { 
      text[index--] = '-'; 
     }  
    } 

    rsgDrawText(&text[index], x - 10, y + 5); 
} 
+0

我想這可能是一個功能,不是嗎?哦,也許以後... – Cubby 2011-06-08 23:55:35

+0

它可能會更有效率。我在那裏分配一個緩衝區。 – Cubby 2011-06-08 23:56:52

3

對不起,這裏是一個更好的。它也適用於整數,但它們的「.000」增加了。

char stringBuffer[50]; 
static const int MAX_STRING_LENGTH = sizeof(stringBuffer) - 1; 

void drawFloat(float value, int x, int y) { 

    int index = 0; 

    int scaledValue = (int)(value * 1000); 

    index = MAX_STRING_LENGTH; 
    stringBuffer[index] = 0; 

    while(scaledValue > 0 || index > MAX_STRING_LENGTH - 4) { 

     index--; 

     if(index == MAX_STRING_LENGTH - 4) { 
      stringBuffer[index--] = '.'; 
     } 

     int digitValue = scaledValue % 10; 

     stringBuffer[index] = '0' + digitValue; 

     scaledValue /= 10; 
    } 

    if(value < 0) { 
     stringBuffer[index--] = '-'; 
    }  

    rsgDrawText(&stringBuffer[index], x - 10, y + 5); 
}