[英]How to make the canvas fit the screen
我正在应用程序中绘制画布,但问题是画布的大小与屏幕的大小不同。 通常,画布仅覆盖屏幕的右下部分。 可以做到使其适合屏幕吗?
以下是其外观的屏幕截图:
这是我的代码:
public class AnimationView extends View
{
private Movie mMovie;
private long mMovieStart;
private static final boolean DECODE_STREAM = true;
private static byte[] streamToBytes(InputStream is) {
ByteArrayOutputStream os = new ByteArrayOutputStream(1024);
byte[] buffer = new byte[1024];
int len;
try {
while ((len = is.read(buffer)) >= 0) {
os.write(buffer, 0, len);
}
} catch (java.io.IOException e) {
}
return os.toByteArray();
}
public AnimationView(Context context,AttributeSet attrs)
{
super(context,attrs);
setFocusable(true);
java.io.InputStream is;
is = context.getResources().openRawResource(R.drawable.flag);
if (DECODE_STREAM) {
mMovie = Movie.decodeStream(is);
} else {
byte[] array = streamToBytes(is);
mMovie = Movie.decodeByteArray(array, 0, array.length);
}
}
@Override
public void onDraw(Canvas canvas) {
long now = android.os.SystemClock.uptimeMillis();
if (mMovieStart == 0) { // first time
mMovieStart = now;
}
if (mMovie != null) {
int dur = mMovie.duration();
if (dur == 0) {
dur = 3000;
}
int relTime = (int) ((now - mMovieStart) % dur);
Log.d("", "real time :: " +relTime);
mMovie.setTime(relTime);
int width = this.getWidth()/2;
int height = this.getHeight()/2;
mMovie.draw(canvas, width, height);
invalidate();
}
}
}
这是XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#074068"
android:orientation="vertical" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
<com.androidqa.AnimationView
android:id="@+id/View"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:adjustViewBounds="true"
android:visibility="gone"
android:background="#074068" />
</LinearLayout>
我认为Movie
是自定义类吗? 我看不到Movie.draw()
int width = this.getWidth()/2;
int height = this.getHeight()/2;
mMovie.draw(canvas, width, height); // this method
但我可以看到您无缘无故地偏移了图像。 又名,开始在中心绘制。 此时图像本身未居中的位置。
在绘制方法的内部绘制图像的内部,在绘制之前缩放图像。 并在原始位置绘制它。
bitmap = Bitmap.createScaledBitmap(bitmap, width, height, true);
canvas.drawBitmap(bitmap, 0, 0, null);
但是将视图的实际高度传递给您的draw方法:
int width = this.getWidth();
int height = this.getHeight();
mMovie.draw(canvas, width, height);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.