首页 > 代码库 > 自定义View--day1
自定义View--day1
public class MyVolumnView extends View { int count_dark = 7; final int MAX_COUNT = 15; Paint paint; Bitmap dark; Bitmap light; final int SPAN = 5; public MyVolumnView(Context context, AttributeSet attrs) { super(context, attrs); paint = new Paint(); dark = BitmapFactory.decodeResource(getResources(), R.drawable.sound_line1); light = BitmapFactory.decodeResource(getResources(), R.drawable.sound_line); } @Override protected void onDraw(Canvas canvas) { // TODO Auto-generated method stub // 画的黑条目 for (int i = 0; i < count_dark; i++) { canvas.drawBitmap(dark, new Rect(0, 0, dark.getWidth(), dark.getHeight()), new Rect(0, i * (dark.getHeight() + SPAN), dark.getWidth(), i * (dark.getHeight() + SPAN) + dark.getHeight()), paint); } // 画亮条目 for (int j = count_dark; j < MAX_COUNT; j++) { canvas.drawBitmap(light, new Rect(0, 0, dark.getWidth(), dark.getHeight()), new Rect(0, j * (dark.getHeight() + SPAN), dark.getWidth(), j * (dark.getHeight() + SPAN) + dark.getHeight()), paint); } super.onDraw(canvas); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { //决定控件的宽高 int realWidth = getRealSize(widthMeasureSpec, true); int realHeight = getRealSize(heightMeasureSpec, false); this.setMeasuredDimension(realWidth, realHeight); } @Override public boolean onTouchEvent(MotionEvent event) { //触摸事件 int action = event.getAction(); float x = 0, y = 0; switch (action) { case MotionEvent.ACTION_DOWN: x = event.getX(); y = event.getY(); break; case MotionEvent.ACTION_MOVE: x = event.getX(); y = event.getY(); break; case MotionEvent.ACTION_UP: x = event.getX(); y = event.getY(); break; default: break; } if (x > dark.getWidth()) { return true; } float percent = y / (MAX_COUNT * dark.getHeight() + (MAX_COUNT - 1) * SPAN); if (percent > 1) { return true; } count_dark = (int) (percent * 15); this.invalidate(); // Log.i("INFO", "count of dark is:"+count_dark); return true; } private int getRealSize(int length, boolean isWidth) { int realSize = 0; int specMode = MeasureSpec.getMode(length); int size = MeasureSpec.getSize(length); int padding = isWidth ? this.getPaddingLeft() + this.getPaddingRight() : this.getPaddingTop() + this.getPaddingBottom(); if (specMode == MeasureSpec.EXACTLY) { realSize = size; } else { realSize = isWidth ? dark.getWidth() + padding : MAX_COUNT * (dark.getHeight() + padding) + (MAX_COUNT - 1) * SPAN; if (specMode == MeasureSpec.UNSPECIFIED) { realSize = Math.min(realSize, size); } } Log.i("INFO", "realSize:" + realSize); return realSize; }}
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。