2022年10月24日 星期一

Flutter學習-Stack練習 橫標製作

 import 'dart:math';


import 'package:flutter/material.dart';

void main() {
runApp(const MyApp());
}

class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);

// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}

class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);


final String title;

@override
State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

@override
Widget build(BuildContext context) {
double w=180; //長條的寬度
double h=64; //長條的高度

//取出文字的大小
final span=TextSpan(
text: "這是橫標",
style: TextStyle(fontSize: 20),
);

final tp=TextPainter(
text: span,
textDirection: TextDirection.rtl,)..layout();
//依文字大小重新給予外部長條的長寬
w=tp.width*2;
h=tp.height;



return Scaffold(

appBar: AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body: Center(
//利用clipRRect裁切
child: ClipRect(
child: Stack(
clipBehavior: Clip.none,
children: [
Container(
color: Colors.red,
width: 320,
height: 320,
),
Positioned(
right: 0,
//left: 0,
top: sqrt(w*w/2-sqrt2*w*h+h*h), //切成剛好大小的公式
child: Transform.rotate(
alignment: Alignment.bottomRight,
angle: 45/180*pi, //由右方中間為0度, 前面為要轉的度數,後面是180*pi(轉成弧度制)
child: Container(
width: w,
height: h,
color: Colors.yellow,
alignment: Alignment.center,
child: Text.rich(span),
),
),
),
],
),
),
),
);
}
}

沒有留言:

張貼留言