Categories

วันศุกร์ที่ 17 กรกฎาคม พ.ศ. 2552

TIP on Android Development

เทคนิคที่สำคัญที่สุดอันหนึ่งของการเขียนโปรแกรมบน Android คือการหลีกเลี่ยงการสร้าง และ ทำลาย object บ่อย ๆ ซึ่งทุก ๆ object ที่ถูกสร้างใน method onDraw จะถูกสร้างและทำลายทิ้ง ทุก ๆ ครั้งที่คุณ refresh หน้าจอ เราจะเพิ่มประสิทธิภาำพให้โปรแกรมได้โดยการย้ายการสร้าง object พวกนี้ (โดยเฉพาะ instance ของ Paint และ Drawable) ไปใว้ใน constructor
public class MyView extends View {
    // Constructor required for in-code creation
    public MyView(Context context) {
         super(context);
    }
    @Override
    protected void onDraw(Canvas canvas) {
         int px = 100;
         int py = 100;
         // Create the new paint brushes
         Paint mTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
         mTextPaint.setColor(Color.WHITE);

         // Define the string.
         String displayText = “Hello World!”;

         // Measure the width of the text string.
         float textWidth = mTextPaint.measureText(displayText);

         // Draw the text string in the center of the control.
         canvas.drawText(displayText, px-textWidth/2, py, mTextPaint);
    }
}
ไปเป็น...
public class MyView extends View {
    // Constructor required for in-code creation
    public MyView(Context context) {
         super(context);
         // Create the new paint brushes
         Paint mTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    }
    @Override
    protected void onDraw(Canvas canvas) {
         int px = 100;
         int py = 100;
         mTextPaint.setColor(Color.WHITE);

         // Define the string.
         String displayText = “Hello World!”;

         // Measure the width of the text string.
         float textWidth = mTextPaint.measureText(displayText);

         // Draw the text string in the center of the control.
         canvas.drawText(displayText, px-textWidth/2, py, mTextPaint);
    }
}

ไม่มีความคิดเห็น:

แสดงความคิดเห็น

Search