我在 imageView 中使用 .png 图像,但方形透明背景仍然出现。我想从 imageView 中删除所有多余的空格。即使在 imageView 中使用 .png 图像,字符之间的额外空格仍然存在。我想给图像上色,所以不希望有多余的空格。在附图中,“3”内空白处的点击事件有效,但我不想要。我只想让点击事件在“3”上起作用。
这是我的 XML。里面没有什么太多的。另外,图中“3”周围的正方形是使用 Paint 绘制的,而不是通过代码绘制的,只是为了澄清 mu 问题。 imageView有一个方形边框,我想根据“3”正确匹配它
<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"
tools:context=".MainActivity" >
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:src="@drawable/image"
android:id="@+id/test_image"
android:scaleType="matrix"
android:background="@null"
android:text="@string/hello_world" />
</RelativeLayout>
我尝试了拉马拉尔的解决方案。它的工作方式更接近所需的内容,但不是很准确。如果我的着色速度非常慢,效果会很好,但如果我开始更快地移动手指,那么空白区域也会着色。这是我正在使用的代码
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) this.findViewById(R.id.test_image);
BitmapFactory.Options decode_options = new BitmapFactory.Options();
decode_options.inMutable = true;
bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.image,decode_options);
canvas = new Canvas(bitmap);
paint = new Paint();
transparentPaint = new Paint();
transparentPaint.setColorFilter(new PorterDuffColorFilter(android.graphics.Color.TRANSPARENT, PorterDuff.Mode.SRC_ATOP));
transparentPaint.setStrokeWidth(5);
paint.setColorFilter(new PorterDuffColorFilter(android.graphics.Color.GREEN, PorterDuff.Mode.SRC_ATOP));
paint.setStrokeWidth(5);
imageView.setScaleType(ScaleType.MATRIX);
imageView.setImageBitmap(bitmap);
imageView.setOnTouchListener(this);
}
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
downx = event.getX();
downy = event.getY();
break;
case MotionEvent.ACTION_MOVE:
upx = event.getX();
upy = event.getY();
Drawable imgDrawable = ((ImageView)v).getDrawable();
Bitmap bitmap = ((BitmapDrawable)imgDrawable).getBitmap();
int color = bitmap.getPixel((int)upx, (int)upy);
if ((color & 0xff000000) == 0x0){//pixel is TRANSPARENT
canvas.drawLine(downx, downy, upx, upy, transparentPaint);
imageView.invalidate();
downx = upx;
downy = upy;
return true;
}else {
canvas.drawLine(downx, downy, upx, upy, paint);
imageView.invalidate();
downx = upx;
downy = upy;
return true;
}
case MotionEvent.ACTION_UP:
upx = event.getX();
upy = event.getY();
break;
case MotionEvent.ACTION_CANCEL:
break;
default:
break;
}
return true;
}
这是该代码的输出。我在代码中使用的图像是简单的“3”,一个 .png 图像,其中除 3 之外的区域都是透明的。
最佳答案
这将解决您的问题。
只需在 imageview 的 xml 文件中添加此属性即可:
android:adjustViewBounds="true"
http://simplifiedandroiddeveloper.blogspot.in/2017/01/remove-empty-space-above-and-below.html
关于android - 在android中使用.png图像从imageView中删除多余的空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21087529/