Skip to content

Instantly share code, notes, and snippets.

@rduplain
Created January 5, 2012 15:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rduplain/1565819 to your computer and use it in GitHub Desktop.
Save rduplain/1565819 to your computer and use it in GitHub Desktop.
Convert dp dimensions to px dimensions, rewriting .xml files in place.
"Convert dp dimensions to px dimensions, rewriting .xml files in place."
# Rewrite all .xml files in res/ with:
# find res -name '*.xml' | xargs python dp2px.py
import decimal
import re
import sys
# scale = getResources().getDisplayMetrics().density; // In Activity.
dip_re = re.compile('"(.*)dp"') # works just as well with sp.
scale = 1.5
def process_file(filename, logfile=sys.stderr):
modified = False
body = ''
for line in open(filename):
match = dip_re.search(line)
if match is not None:
modified = True
dips = decimal.Decimal(match.group(1))
pixels = dips * decimal.Decimal(scale)
body += dip_re.sub('"{0}px"'.format(pixels), line)
else:
body += line
if modified:
logfile.write('Updating {0}.\n'.format(filename))
open(filename, 'w').write(body)
if __name__ == '__main__':
if len(sys.argv) == 1:
sys.stderr.write('usage: {0} xml_filename\n'.format(sys.argv[0]))
sys.exit(1)
for filename in sys.argv[1:]:
process_file(filename)
@rduplain
Copy link
Author

rduplain commented Jan 5, 2012

Why would you want to do this? If you are working with a device that does not support scaling, either by limitation or by bug.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment