Android:定义 onDraw Canvas 大小

标签 android android-layout android-canvas ondraw

我现在删除了旧代码,因为它没有按我的预期工作。我试图在屏幕的某个部分使用 onDraw Canvas 功能,以便我的绘图周围仍然可以有按钮和其他文本。

***编辑***

我现在已经成功解决了这个问题。很多建议都是有帮助的,但我就是无法让它按照我想要的方式工作。这可能更多是我的错,所以感谢所有提供建议的人。这是我解决问题的方法。

*1。首先在布局文件中定义一个 View 。

<view
class="com.project.MainActivity.Drawing"
android:id="@+id/drawing_area"
android:layout_width="700dp"
android:layout_height="900dp"
android:layout_centerInParent="true"/>

*2。然后使用以下代码创建一个单独的java类文件:

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

public Drawing(Context context) {
super(context);
}

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

@Override
protected void onDraw(Canvas canvas) {  
super.onDraw(canvas);

//Draw Image Here//

}

*3。然后从主 Activity 中调用绘图:

public class MainActivity extends Activity {

private Drawing mDrawingArea;

@Override
public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.percentage_count_layout);
  mDrawingArea = (Drawing)findViewById(R.id.drawing_area);  
}

最佳答案

在您的 View 类中,您需要重写 onMeasure() 方法。这是您要求特定 View 大小的地方。有一些关于这个主题的官方 Android 教程,我将在我的计算机上使用链接后编辑这篇文章。

编辑:

看看这个 Android article about creating custom components. 。具体请查看标题为“扩展 onDraw() 和 onMeasure()”的部分。引用:

onMeasure() is a little more involved. onMeasure() is a critical piece of the rendering contract between your component and its container. onMeasure() should be overridden to efficiently and accurately report the measurements of its contained parts. This is made slightly more complex by the requirements of limits from the parent (which are passed in to the onMeasure() method) and by the requirement to call the setMeasuredDimension() method with the measured width and height once they have been calculated. If you fail to call this method from an overridden onMeasure() method, the result will be an exception at measurement time.

文章中的进一步内容:

Your component's onMeasure() method should calculate a measurement width and height which will be required to render the component. It should try to stay within the specifications passed in, although it can choose to exceed them (in this case, the parent can choose what to do, including clipping, scrolling, throwing an exception, or asking the onMeasure() to try again, perhaps with different measurement specifications).

有一个 CustomView 示例可用作演示,但不幸的是,开发人员网站已更改(变得更糟!),因此除了通过 SDK 管理器下载之外,它不可用。查看页面here了解更多说明。

关于Android:定义 onDraw Canvas 大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14485420/

相关文章:

android - 如何正确设置 LayoutParams

Android 应用程序布局被大文本破坏

android - 如何使用 android View 的 IsDirty() 属性

android - 如何创建 Bitmap 形式的 Drawable 对象

android - 折叠工具栏布局第一次没有展开,pin 不起作用

android - 如何为 GeoDataApi.getAutocompletePredictions 使用位置偏差(附近)?

android - 如何将 .pcm 文件转换为 .wav 或 .mp3?

Android 圆圈操作

android - 如何在 Android 中实现一个行为类似于具有属性 "float:left"的 HTML block 的 View ?

java - 自定义View drawArc,检测用户在弧形绘制路径上的触摸