java画布矩形位置
我是Android上画布的新手。我试图在屏幕中央画一个正方形,我想在单击按钮时增大或减小正方形的大小。问题是我不明白正方形的位置。
当我添加这样的代码时,它的位置正确(5左5顶):canvas.drawRect(5, 5, sideLength, sideLength, mPaint);
但是我想在屏幕中央画这个正方形,就像我之前提到的。
我已经试过了,但是方块没有出现在屏幕上:canvas.drawRect(getWidth()/2, getHeight()/2, sideLength, sideLength, mPaint);
如果你能帮我找到解决办法,那就太好了
主要活动。xml
<安卓.support.constraint.ConstraintLayout
xmlns:安卓="http://schemas.安卓.com/apk/res/安卓"
xmlns:app="http://schemas.安卓.com/apk/res-auto"
xmlns:tools="http://schemas.安卓.com/tools"
安卓:id="@+id/linearLayout"
安卓:layout_width="match_parent"
安卓:layout_height="match_parent"
安卓:orientation="vertical"
tools:context=".MainActivity" >
<FrameLayout
安卓:id="@+id/frameLayout"
安卓:layout_width="match_parent"
安卓:layout_height="0dp"
app:layout_constraintBottom_toTopOf="@id/button"
app:layout_constraintTop_toTopOf="parent"/>
<Button
安卓:id="@+id/button"
安卓:layout_width="match_parent"
安卓:layout_height="wrap_content"
安卓:text="Button"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"/>
</安卓.support.constraint.ConstraintLayout>
主要活动。爪哇
public class MainActivity extends AppCompatActivity {
FrameLayout frameLayout;
MyView myView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
frameLayout = findViewById(R.id.frameLayout);
myView = new MyView(this,200);
frameLayout.addView(myView);
findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
frameLayout.removeView(myView);
myView = new MyView(MainActivity.this,600);
frameLayout.addView(myView);
}
});
}
}
我的观点。爪哇
public class MyView extends View {
Paint mPaint;
int sideLength;
public MyView(Context context){
super(context);
}
public MyView(Context context,int sideLength) {
super(context);
this.sideLength = sideLength;
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setStyle(Paint.Style.FILL);
mPaint.setColor(Color.BLUE);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawRect(getWidth()/2, getHeight()/2, sideLength, sideLength, mPaint);
}
}
# 1 楼答案
getWidth()/2
和getheight()/2
将为您提供容器的中心坐标。 假设您的容器是一个尺寸为(2000, 2000) in pixels
的完美正方形,那么您的中心坐标将是(10001000)。记住这一点,您正试图在坐标1000
处绘制正方形的左侧,在坐标1000处绘制正方形的顶部现在下一部分就是问题所在。您正试图在坐标
600
处绘制右侧,在坐标600
处绘制底部绘制矩形和正方形时,应注意以下事项:
下面是在FrameLayout的中心绘制正方形的工作代码
MyView.java
activity_main.xml