80,362
社区成员
发帖
与我相关
我的任务
分享
public class MyView extends View {
private int radius; // 圆半径
private Paint paint;
private float circleX; // 圆心x坐标
private float circleY; // 圆心y坐标
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
initPaint();
}
private void initPaint() {
paint = new Paint();
paint.setAntiAlias(true);
paint.setColor(Color.RED);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
// TODO Auto-generated method stub
super.onSizeChanged(w, h, oldw, oldh);
circleX = w / 2;
circleY = h / 2;
radius = Math.min(w, h) / 2;
}
@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
canvas.drawCircle(circleX, circleY, radius, paint);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch(event.getAction()) {
case MotionEvent.ACTION_DOWN:
return true;
case MotionEvent.ACTION_MOVE:
circleX = event.getX();
circleY = event.getY();
break;
}
postInvalidate();
return super.onTouchEvent(event);
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#0F0">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_alignParentBottom="true"
android:background="#00F"
android:gravity="center" >
<com.example.testmove.MyView
android:layout_width="50dp"
android:layout_height="50dp"
/>
</LinearLayout>
</RelativeLayout>
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}