在ImageView上绘图
问题描述:
我想绘制ImageView(就像一个简单的绘画,但只是在图像上)。我创建了一个自定义的MyImageView类,它扩展了ImageView,我重写了onDraw。我希望ImageView位于屏幕的中心。在ImageView上绘图
当我使用一种布局时,图像出现在左上角,我可以在上面画出没有问题的图像。
当我使用不同的布局,图像出现在屏幕*但画布仍然停留在左上角这个小的小矩形。因此,当我尝试绘制图像时,我只能在左上角进行绘制,并在中间的图像上显示变化。
在我的MainActivity我设置:
myImageView = (MyImageView) findViewById(R.id.pdfView);
// I also extract the bitmap myBitmap from the pdf ...
// and pass it to the ImageView
myImageView.setImageBitmap(myBitmap);
// and I set the Canvas too:
Canvas myCanvas = new Canvas(myBitmap);
myImageView.setMyCanvas(myCanvas);
然后这里是MyImageView的关键部分:
public class MyImageView extends
android.support.v7.widget.AppCompatImageView {
// variables...
public MyImageView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
setupDrawing();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawPath(drawPath, drawPaint);
}
private void setupDrawing() { //...usual stuff here }
@Override
public boolean onTouchEvent(MotionEvent event) { //...usual stuff here }
public void setMyCanvas(Canvas canvas) { this.myCanvas = canvas; }
我一定要在MyImageView或添加/更改某事MainActivity,以便画布仅位于ImageView的顶部或至少在整个屏幕上延伸?
答
for,ImageView将在屏幕中心。修改您的布局如下
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
android:background="#EEEEEE">
<com.example.android.samplepaint.MyImageView
android:id="@+id/pdfView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:scaleType="fitXY"
android:layout_gravity="center_horizontal"
android:background="@android:color/white" />
</LinearLayout>
答
画布原点和ImageView scaleType或重力之间没有关系。
画布的X,Y原点始终是视图的左上角,如果您想在视图的其他部分进行绘制,则需要自行翻译坐标。
ADDED 首先要理解的是,画布不仅用于绘制所有视图,而且还用于绘制您选择的图像。
居中路径绘制,那么你需要做这样的事情在你的onDraw不是一个规划问题
canvas.save();
canvas.translate((getWidth() - pathWidth)/2, (getHeight() - pathHeight)/2);
canvas.drawPath(drawPath, drawPaint);
canvas.restore();
更多的是算术之一。
答
我认为原因在于您的布局选择。由于屏幕适应的问题,每个布局需要绑定到元素,而某些布局默认为左上角。
你可以在这里添加你的onDraw()方法的代码。你有硬编码的价值吗?另外,第二种情况看起来像是将宽度和高度设置为匹配图像视图的match_parent,这就是为什么您将整个区域作为画布。 – user2520215
我想加入 android:gravity =“center” 到你的线性布局应该使它按照需要工作。 – user2520215