만족

[Android Studio] Custom View 본문

[Android Studio] Custom View

FrontEnd/Android Satisfaction 2018. 1. 17. 03:18

기본적으로 존재하는 뷰 외에도 사용자가 직접 View Class를 상속받아서 개발자 임의로 View를 만들어 사용할 수 있다.


package com.example.windows7.myapplication;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;

/**
* Created by WINDOWS7 on 2018-01-16.
*/

public class CustomView extends View {
private Paint paint= null;
public CustomView(Context context){
super(context);
}

//화면에 뷰가 표시될 때 호출되는 method
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);

// 붉은색으로 전부 칠해진 정사각형
paint= new Paint();
paint.setColor(Color.RED);
canvas.drawRect(100, 100, 200, 200, paint);

// 붉은색으로 테두리만 칠해진 정사각형
paint= new Paint();
paint.setStyle(Paint.Style.STROKE);
paint.setColor(Color.RED);
paint.setStrokeWidth(2);
canvas.drawRect(200, 100, 300, 200, paint);

// 투명도가 약 0.5인 파란색 정사각형
paint= new Paint();
paint.setARGB(128, 0,0,255);
paint.setStyle(Paint.Style.FILL);
canvas.drawRect(100, 200, 200, 300, paint);

//테두리가 점선으로 된 초록색 정사각형
paint= new Paint();
DashPathEffect dashPathEffect= new DashPathEffect(new float[]{5,5}, 1);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(3.0F);
paint.setPathEffect(dashPathEffect);
paint.setColor(Color.GREEN);
canvas.drawRect(200, 200, 300, 300, paint);

//텍스트
paint= new Paint();
paint.setColor(Color.MAGENTA);
paint.setStrokeWidth(1);
paint.setTextSize(30);

canvas.drawText("No AntiAlias", 400, 300, paint);
paint.setAntiAlias(true);
canvas.drawText("Ok AntiAlias", 400, 400, paint);
}

@Override
public boolean onTouchEvent(MotionEvent event) {
if(event.getAction()== MotionEvent.ACTION_DOWN){
Toast.makeText(super.getContext(), "X: "+ event.getX()+ ", Y:"+ event.getY(), Toast.LENGTH_LONG).show();
}

return super.onTouchEvent(event);
}
}


작성중



Comments