Mental Jetsam

By Peter Finch

Archive for July, 2012

Calculating Android canvas device pixels sizes

Posted by pcfinch on July 26, 2012

When drawing on a Android Canvas, it’s important to take into consideration the different pixel densities when rendering lines and text. Using “pixels” can make things too small on high resolution screens. Using DIP instead of pixels is a good way to keep things a similar size physical size on the screen and the following code can be used to map DP values to pixel based values.

int dpSize = 5 ;
DisplayMetrics dm = getResources().getDisplayMetrics() ;
float inPixels = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpSize , dm);
...
paint.setStrokeWidth(inPixels) ;
...
paint.setTextSize(inPixels * 3);
...

Posted in Programming | Leave a Comment »

Hiding the Android soft keyboard

Posted by pcfinch on July 19, 2012

This sounded so simple… but it wasn’t as easy as I thought. All I wanted to do was hide the soft keyboard when I was switching (using a ViewFlipper) to a view that did not require it. This is what I ended up doing and it seems to work.

ViewFlipper flipper = (ViewFlipper)this.findViewById(R.id.viewFlipper_main) ; // Any active view will do
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE) ;
imm.hideSoftInputFromWindow(flipper.getApplicationWindowToken(), 0);
flipper.setDisplayedChild(1) ;

Posted in Programming | 1 Comment »

Java Hello World

Posted by pcfinch on July 11, 2012

This is a standard “hello world” program that I use when testing a java installation to make sure everything works.

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;

import javax.swing.JFrame;
import javax.swing.JPanel;


public class MyFrame extends JFrame {
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		MyFrame mf = new MyFrame() ;
	}
	
	protected MyFrame() {
		this.setTitle("MyFrame") ;
		this.setSize(800, 600) ;
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) ;
		this.getContentPane().add(new JPanel() {
			public void paintComponent(Graphics g) {
				Graphics2D g2 = (Graphics2D)g ;
				g2.setColor(Color.blue) ;				
				g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, 
						RenderingHints.VALUE_ANTIALIAS_ON);
				g2.drawLine(0, 0, this.getWidth(),  this.getHeight()) ;
				g2.drawOval(0, 0, this.getWidth(),  this.getHeight()) ;
				g2.drawString("Hello World", this.getWidth() /2 , this.getHeight() /2) ;
			}			
		}) ;
		this.setVisible(true) ;
	}

}

Posted in Uncategorized | Leave a Comment »