简体   繁体   English

Android:如何制作可滚动的画布?

[英]Android: How do I make a scrollable Canvas?

I am writing an app.我正在编写一个应用程序。 One aspect of it is lines being drawn over an image.它的一个方面是在图像上绘制线条。 Here's the practice code I've been working with:这是我一直在使用的练习代码:

public class DrawView extends View { Paint paint = new Paint(); public class DrawView extends View { Paintpaint = new Paint();

private void init() {
    paint.setColor(Color.BLACK);
}

public DrawView(Context context) {
    super(context);
    init();
}

public DrawView(Context context, AttributeSet attrs) {
    super(context, attrs);
    init();
}

public DrawView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    init();
}

@Override
public void onDraw(Canvas canvas) {
    paint.setStrokeWidth(20);
    canvas.drawLine(100, 100, 20, 20, paint);
    canvas.drawLine(20, 0, 0, 20, paint);

}

}

I want the Canvas to be fairly large, so I need people to be able to scroll in both directions (left/right and up/down).我希望画布相当大,所以我需要人们能够在两个方向(左/右和上/下)滚动。 How do I accomplish this?我该如何实现? I'm unfamiliar with the Canvas class so any help will be appreciated.我不熟悉 Canvas 类,所以任何帮助将不胜感激。

If you want to draw on canvas with your custom height and width you have to call setContentView(android.view.View yourView , android.view.Viewgroup.LayoutParam yourLayout) in your activity class.Because by default setContentView(View view) method use full width and height.So you have to use its overloaded method with two parameter along with your desired.如果你想用你的自定义高度和宽度在画布上绘制你必须在你的活动类中调用 setContentView(android.view.View yourView , android.view.Viewgroup.LayoutParam yourLayout) 。因为默认情况下 setContentView(View view) 方法使用全宽和全高。所以你必须使用它的重载方法和你想要的两个参数。 See documentation for more info.And don`t use only LayoutParams() constructor to create its object.有关更多信息,请参阅文档。不要仅使用 LayoutParams() 构造函数来创建其对象。 Use it by writing its full path like android.view.ViewGroup.LayoutParams.通过编写其完整路径(如 android.view.ViewGroup.LayoutParams)来使用它。 Because there are some other classes with same name in Android SDK.因为在 Android SDK 中还有一些同名的类。

MyView customView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    customView = new MyView(getApplicationContext());
    android.view.ViewGroup.LayoutParams lp = new android.view.ViewGroup.LayoutParams(100,200);//100 is width and 200 is height
    setContentView(customView, lp);
    customView.setOnClickListener(this);

}`  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM