月月月熊~ 2021-09-08 16:30 采纳率: 75%
浏览 74
已采纳

android studio 用canvas画图drawline 不显示

class CustomView extends View{
    Paint paint;
    public CustomView(Context context) {
        super(context);
        paint = new Paint(); 
        paint.setColor(Color.YELLOW);
        paint.setStrokeJoin(Paint.Join.ROUND);
        paint.setStrokeCap(Paint.Cap.ROUND);
        paint.setStrokeWidth(10f);
    }
   
    @Override
    protected void onDraw(Canvas canvas) {
        canvas.drawColor(Color.RED);   
        canvas.drawLine(10, 10, 100, 100, paint);}
}

为什么代码可以运行的 但是画的线没显示

  • 写回答

2条回答 默认 最新

  • 小张同志正在划水 2021-09-08 17:12
    关注
    
    public class CustomView extends View {
        Paint paint;
    
        public CustomView(Context context) {
            super(context);
            init();
        }
    
        public void init() {
            paint = new Paint();
            paint.setColor(Color.YELLOW);
            paint.setStrokeJoin(Paint.Join.ROUND);
            paint.setStrokeCap(Paint.Cap.ROUND);
            paint.setStrokeWidth(10f);
        }
    
        public CustomView(Context context, @Nullable AttributeSet attrs) {
            super(context, attrs);
            init();
    
        }
    
        public CustomView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
            super(context, attrs, defStyleAttr);
        }
    
        @Override
        protected void onDraw(Canvas canvas) {
            canvas.drawColor(Color.RED);
            canvas.drawLine(10, 10, 100, 100, paint);
        }
    }
    

    这是自定义view,
    然后去你的layout文件夹下的资源文件,比如activity_main.xml,加入你的View
    比如:

    
    <?xml version="1.0" encoding="utf-8"?>
    <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".demoIntentActivity">
    
        <你项目的包名.CustomView
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    </androidx.constraintlayout.widget.ConstraintLayout>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 已采纳回答 9月13日
  • 创建了问题 9月8日

悬赏问题

  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥30 python代码,帮调试,帮帮忙吧