2011年3月26日土曜日

Android -- Viewクラス

久々なので思い出しながらまとめます。

■画像描画
画像描画には2つの方法がある

  • main.xmlででの表示
  • Viewerクラスを継承して新規に作成しての表示

Viewerクラスを継承してのMyViewerを表示にはmain.xmlに独自Viewerの
パスを指定する必要がる。(com.hogeがそれ。)





なお、以下のどっちでも表示できる。

  setContentView(R.layout.main);
//setContentView(new MyView(this));

main.xmlを使用したときは、Viewerクラスの引数2つのコンストラクタが呼ばれる。

■画像表示


画像表示には2とおりある

  • BitmapFactoryで画像を作成し、それをCanvasで表示
  • Resourcesでgetした画像をDrawableで表示

ということで以下、Viewソース

public class MyView extends View{
 private Context context;
// private Bitmap image;
 private Drawable drawable;

 public MyView(Context context) {
  super(context);
  this.context = context;
 }

 // main.xml使用時はこっちが呼ばれる
 public MyView(Context context, AttributeSet attrs) {
  super(context);
  this.context = context;

  Resources resources = context.getResources();
//  image = BitmapFactory.decodeResource(resources, R.drawable.pose08_g);
  drawable = resources.getDrawable(R.drawable.pose08_g);
 }

 protected void onDraw(Canvas c) {
  super.onDraw(c);
  c.drawColor(Color.GREEN);

/*  if (image != null) {
   c.drawBitmap(image, 10, 10, new Paint());
  }
*/
  if (drawable != null) {
   drawable.setBounds(10, 10, 310, 310);
   drawable.draw(c);
  }
  int w = this.getWidth();
  int h = this.getHeight();
  Paint p = new Paint();
  p.setStyle(Style.STROKE);
  p.setColor(Color.DKGRAY);
  c.drawRect(new Rect(5, 5, w-10, h-10), p);

  for (int i = 0; i <10; i++){
   Paint p2 = new Paint();
   p2.setStyle(Style.FILL);
   p2.setColor(Color.rgb(25*i, 0, 0));
   c.drawCircle(25 * i + 125, 25 * i +125, 100, p2);
  }
 }

}


0 件のコメント:

試験結果

昨日の夜、CGーArtsエンジニアのベーシック、エキスパートの自己採点をした。 実は日曜日には回答が出ていたけど、自信がなく採点するのもやめようかと思っていたがタイミング&勢いでやってしまった。 <結果>  ベーシック:85点  エキスパート:72.5点 70点以上で合格なので...