Guest User

Untitled

a guest
Jan 18th, 2018
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.54 KB | None | 0 0
  1. /**
  2. * Run convertVectorsToPngs() test, get the pngs from the device by "adb pull <the path>" and paste the res folders
  3. * into your android project.
  4. *
  5. * @author PƤr Amsen 01/2018
  6. */
  7. @RunWith(AndroidJUnit4::class)
  8. class Vector2Png {
  9. lateinit var context: Context
  10. lateinit var baseDir: File
  11.  
  12. @Before
  13. fun before() {
  14. context = InstrumentationRegistry.getTargetContext()
  15. baseDir = File(context.getExternalFilesDir(Environment.DIRECTORY_PICTURES), "converted_res").apply { mkdir() }
  16. }
  17.  
  18. @Test
  19. fun convertVectorsToPngs() {
  20. val drawableResources = R.drawable()
  21. val c = R.drawable::class.java
  22. val fields = c.declaredFields
  23.  
  24. val max = fields.size
  25. val excluded = listOf("EXCLUSIONS HERE")
  26. val configs = listOf(1f to "mdpi", 1.5f to "hdpi", 2f to "xhdpi", 3f to "xxhdpi", 4f to "xxxhdpi")
  27.  
  28. for (i in 0 until max) {
  29. val resourceId: Int
  30. try {
  31. resourceId = fields[i].getInt(drawableResources)
  32. } catch (e: Exception) {
  33. continue
  34. }
  35.  
  36. val name = context.resources.getResourceEntryName(resourceId)
  37. if(excluded.contains(name)) continue
  38.  
  39. configs.forEach { convertToPng(name, resourceId, it.first, it.second) }
  40. }
  41.  
  42. Assert.assertTrue(true)
  43. }
  44.  
  45. fun convertToPng(name: String, resId: Int, multiplier: Float, dirSuffix: String) {
  46. val xpp: XmlResourceParser
  47.  
  48. try {
  49. xpp = context.resources.getXml(resId)
  50. } catch (e: Exception) {
  51. return
  52. }
  53.  
  54. xpp.next()
  55. if (xpp.name != "vector") xpp.next()
  56. if (xpp.name != "vector") return
  57.  
  58. val count = xpp.attributeCount
  59. val map = (0 until count).map { xpp.getAttributeName(it) to it }.toMap()
  60. val w = xpp.getAttributeValue(map["width"]!!).removeSuffix("dip").toFloat() * multiplier
  61. val h = xpp.getAttributeValue(map["height"]!!).removeSuffix("dip").toFloat() * multiplier
  62.  
  63. val b = Bitmap.createBitmap(w.toInt(), h.toInt(), Bitmap.Config.ARGB_8888)
  64. val c = Canvas(b)
  65. val d = ContextCompat.getDrawable(context, resId)!!
  66. d.bounds = Rect(0, 0, w.toInt(), h.toInt())
  67. d.draw(c)
  68.  
  69. val dir = File(baseDir, "drawable-$dirSuffix").apply {
  70. mkdir()
  71. listFiles().forEach { delete() }
  72. }
  73. b.compress(Bitmap.CompressFormat.PNG, 100, FileOutputStream(File(dir, "$name.png")))
  74.  
  75. println("=== ${dir.absolutePath}")
  76.  
  77. Assert.assertTrue(true)
  78. }
  79. }
Add Comment
Please, Sign In to add comment