月月月熊~ 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日

悬赏问题

  • ¥170 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥15 键盘指令混乱情况下的启动盘系统重装