안드로이드 개발의 사용자 정의 View Drawable을 통해 아이콘 그리기

//주로 Drawable 객체를 통해 아이콘 그리기
public class MyView extends View{


    private float mCircleRadius;
    private int defaultHeight;
    private Drawable mIcon;
    private Rect rect;


    public MyView(Context context) {
        super(context);
        init();

    }

    private void init() {
        defaultStepIndicatorNum = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 40, getResources().getDisplayMetrics());

        mCircleRadius = 0.5f * defaultHeight;

        mIcon = ContextCompat.getDrawable(getContext(), R.drawable.m);
    }

    public MyView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();

    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        setBackgroundColor(Color.TRANSPARENT);

        // 
        mIcon.setBounds(rect);
        mIcon.draw(canvas);

    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int  width = MeasureSpec.getSize(widthMeasureSpec);
        int height = (int) (defaultHeight*1.5);
        if(MeasureSpec.UNSPECIFIED != MeasureSpec.getMode(heightMeasureSpec))
        {
            height = Math.min(height, MeasureSpec.getSize(heightMeasureSpec));
        }
        setMeasuredDimension(width,height);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);

        rect = new Rect((int) (getWidth()/2 - mCircleRadius), (int)(getHeight()/2-mCircleRadius) , (int) (getWidth()/2+ mCircleRadius), (int)(getHeight()/2+mCircleRadius));
    }
}

좋은 웹페이지 즐겨찾기