Flutter 그리기 Paint

6491 단어 flutter

Flutter의 그리기는 주로 두 개의widget:CustomPainter,CustomPaint와 관련된다


CustomPainter: 캔버스의 구성 요소를 제공합니다.다음과 같은 몇 가지 주요 매개변수가 있습니다.


a. painter: 그려진 객체는 CustomPaint입니다.그것의 그림은children 이전에 그려진 것이다.children을 설정하면 이painter가 그린 내용을 덮어씁니다.b. foregroundPainter: 그려진 객체는 CustomPaint입니다.그것의 그림은children 다음에 그려집니다.이painter가 그린 내용은children을 덮어씁니다.c. size: 영역의 크기를 그립니다.child가 있으면 이 속성을 무시하고 child의 size를 사용합니다.d. child :

CustomPaint: 추상적인 클래스입니다. 그리는 논리를 실현하려면 추상적인 클래스를 계승하고, 추상적인 클래스와shouldRepaint 방법을 실현해야 합니다.


void paint(Canvas canvas, Size size);: 안에서 구체적인 제도 논리를 실현하다.


- canvas: 캔버스 – size: 캔버스의 크기

bool shouldRepaint(covariant CustomPainter oldDelegate); : 다시 그리기 여부를 조정합니다.


그리다


Paint 붓


자주 사용하는 매개 변수를 소개합니다: (1)color: 붓의 색 (2)strokeWidth: 선의 너비 (3)style: 충전 모드, 두 가지가 있습니다:PaintingStyle.fill: 채우기;PaintingStyle.stroke: 비어 있음(4) strokeCap: (5)blendMode: 중첩된 부분의 처리로 일반적으로 Image를 캡처한 후에 Image를 합쳐서 사용합니다.a. src: 원본 그림만 표시 b. dst: 목표 그림만 표시 c. srcOver: 모두 표시 중첩 부분은 src가 dst의 상단에 덮어쓰기;d. dstOver: 모두 표시되며 중첩 부분은 dst가 src의 위쪽을 덮어씁니다.e. srcIn;//중첩된 부분의 src 그림만 표시하고 투명한 부분도 표시하지 않습니다.f. dstIn;//중첩된 부분의 dst 그림만 표시하고 투명한 부분도 표시하지 않습니다.아직 말하지 않은 것이 많으니 쓸 때 스스로 주석을 보아라.
p = Paint()
  ..color = Colors.orange //  
  ..strokeWidth = 2.0 //  
  ..style = PaintingStyle.stroke // fill:  , stroke:  
  ..strokeCap = StrokeCap.butt //  
  ..blendMode = BlendMode.dstIn; //  ,clear,src, dst, srcIn,dstIn 。

선 세그먼트 그리기

//  
//  
//  
canvas.drawLine(Offset(10, 10), Offset(100, 100), p);

사각형 그리기


직사각형을 그리는 데는 Rect가 필요하고, React의 생성은 Offset과 Size를 통해 할 수 있으며, Offset은 그의 왼쪽 상단의 좌표 Size를 결정하여 그의 크기를 결정합니다.Rect rect = offset & size;
//  
Size size = Size(200, 300);
//  
Offset offset = Offset(200, 200);
//  Rect, ?  ! ---> 
Rect rect = offset & size;
canvas.drawRect(
    rect,
    Paint()
      ..color = Colors.red
      ..strokeWidth = 3.0);
/// A Rect can be created with one its constructors or from an [Offset] and a /// [Size] using the `&` operator: /// /// dart///Rect myRect = const Offset(1.0, 2.0) & const Size(3.0, 4.0);///```
####  
 Path moveTo lineTo ,
void moveTo(double x, double y):  (x,y) 。
void lineTo(double x, double y):  (x,y) 。
canvas.drawPath(     Path()       …moveTo(30, 200)       …lineTo(200, 200)       …lineTo(100, 300)       …lineTo(50, 330)       …lineTo(30, 300)       …close(),     Paint()       …color = Colors.lightBlue       …strokeWidth = 1.0);
####  
//첫 번째 파라미터는 원점 좌표//두 번째 파라미터는 반경//세 번째 파라미터는 화필 canvas.drawCircle(Offset(100, 100), 50, p);
####  
``` 
// Path   moveTo, lineTo .
canvas.drawShadow(
    Path()
      ..moveTo(30.0, 30.0)
      ..lineTo(320.0, 30.0)
      ..lineTo(120.0, 160.0)
      ..lineTo(30.0, 160.0)
      ..close(),
//  
    Colors.blue, 
//  
    3,
    false);

텍스트 그리기

ParagraphBuilder pb = ParagraphBuilder(ParagraphStyle(
  textAlign: TextAlign.left, //  
  fontWeight: FontWeight.w600, //  
  fontStyle: FontStyle.normal, //   or  
  fontSize: 18,
))
  ..pushStyle(dartUi.TextStyle(color: Colors.black26))
  ..addText('''
  //  
  //  
  canvas.drawShadow(
    Path()
      ..moveTo(30.0, 30.0)
      ..lineTo(320.0, 30.0)
      ..lineTo(120.0, 160.0)
      ..lineTo(30.0, 160.0)
      ..close(),
    Colors.blue,
    3,
    false);
      ''');
//  
ParagraphConstraints pc =
    ParagraphConstraints(width: 350.0);  
Paragraph paragraph = pb.build()..layout(pc);
canvas.drawParagraph(paragraph, Offset(30, 300));

Image 그리기


그리는 코드는 다음과 같습니다. 물론 그는 여러 가지 그리는 방식이 있습니다. (drawImage,drawImageRect,drawImageNine)코드는 보기에는 매우 간단하지만, 만약 네가 직접 이렇게 쓰면, 잘못 보고될 것이다.오랫동안 나를 괴롭혔는데 마지막에 찾아낸 이유는 그림의 마운트가 시간이 걸리기 때문이다. 이 안에 마운트하지 말고 밖에 마운트가 끝난 후에 파라미터를 통해CustomPainter에 전송하면 틀리지 않을 것이다.당신이 직접 여기에 이미지를 불러오고 Future의then에서 아래 코드를 호출하는 것을 믿지 않아도 안 돼요!!!보통 canvas.drawImageRect를 사용하여 canvas 대신 그립니다.drawImage. canvas.drawImageRect는 너비를 지정하여 캡처할 수 있습니다.원본 코드를 보면drawImage의 내부도drawImageRect로 이루어진 것을 발견할 수 있습니다.다음을 사용합니다.
canvas.drawImage(
    image, dartUi.Offset(0, image.height.toDouble() + 30), Paint());
canvas.drawImageRect(
    image,
    //  -- ( 0,0,  60 )
    Rect.fromLTWH(0, 0, 60, 60), 
         //  
    Rect.fromLTWH(0, 0, image.width.toDouble(), image.height.toDouble()),
    Paint());

그림을 그리는 것을 통해 그림을 캡처하는 기능을 실현하다

//  , (60, 60, 190, 90)
canvas.clipRect(Rect.fromLTWH(60, 60, 190, 90));
안드로이드와 유사하게 캔버스를 재단하는 기능을 통해 특수한 그림을 그릴 수 있다.일반적으로 재단하기 전에 canvas를 호출합니다.store () 는 현재 화포를 저장합니다. 재단된 화포에 관련 작업을 끝낸 후에 canvas를 통과할 수 있습니다.restore () 를 사용하여 이전의 화포를 복구합니다.  canvas.store (): 현재 캔버스 저장restore (): 재단하기 전의 캔버스 (이전에 저장한) 를 복원하고 이 두 개를 쌍으로 만들어야 합니다.뛸 수 있는 코드:
import 'package:flutter/material.dart';


void main() =>
    runApp(
        StartPage()
    );

class StartPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: TestPage(),
    );
  }
}


class TestPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("flutter  demo"),),
      body: CustomPaint(foregroundPainter: PaintDemo(),),
    );
  }
}

class PaintDemo extends CustomPainter {
  Paint _paint;

  PaintDemo() {
    _paint = Paint()
      ..color = Colors.orange //  
      ..strokeWidth = 2.0 //  
      ..style = PaintingStyle.fill // fill:  , stroke:  
    ;
  }

  @override
  void paint(Canvas canvas, Size size) {
    canvas.drawLine(Offset(10, 10), Offset(60, 10), _paint);

    canvas.drawCircle(Offset(100, 100), 50, _paint);

    Size size = Size(200, 300);
    //  Offset Size Rect,Offset      Size  
    Rect rect = Offset(200, 200) & size;
    canvas.drawRect(
        rect,
        Paint()
          ..color = Colors.red
          ..strokeWidth = 3.0);

    //  
    canvas.drawShadow(
        Path()
          ..moveTo(30.0, 500.0)
          ..lineTo(320.0, 500.0)..lineTo(120.0, 660.0)..lineTo(30.0, 660.0)
          ..close(),
        Colors.blue,
        3,
        false);
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) {
    return true;
  }
}

이제 Flutter의 그림에 대해 소개한 것은 많지 않으니 바로잡아 주십시오.그림 그리기에 관해서는 코드가 좀 많아서 올리지 않았습니다. 메모가 필요합니다.

좋은 웹페이지 즐겨찾기