探索HarmonyOS NEXT強大的圖形渲染能力,從圖片展示到自定義繪圖
HarmonyOS NEXT作為華為自主研發的操作系統,為開發者提供了一套豐富而強大的圖形渲染能力。無論是顯示圖片、繪制幾何圖形,還是實現復雜的自定義繪圖,鴻蒙都提供了簡潔而高效的解決方案。
本文將詳細介紹鴻蒙NEXT中三種主要的圖形處理方式:圖片顯示、幾何圖形繪制和畫布自定義繪制。
1. 圖片顯示(Image組件)
Image組件是鴻蒙中用于顯示圖片的核心組件,它支持多種圖片格式和源類型,讓開發者能夠靈活地在應用中展示圖像內容。
基本用法和數據源類型
Image組件支持多種數據源,只需簡單調用即可顯示不同來源的圖片:
typescript
// 本地資源 Image('images/panda.jpg').width(100)// Resource資源 Image($r('app.media.cat')).width(100)// 網絡資源(需要申請權限) Image('https://example.com/example.JPG').width(200)// 媒體庫資源 Image('file://media/Photos/5').width(200)// Base64資源 Image('data:image/png;base64,...').width(100)// PixelMap像素圖 @State image: PixelMap | undefined = undefined Image(this.image).width(100).height(100)
網絡圖片權限申請
使用網絡圖片時,需要在module.json5文件中聲明網絡訪問權限:
json
{"module": {"requestPermissions": [{"name": "ohos.permission.INTERNET"}]} }
常用屬性配置
Image組件提供了一系列屬性用于控制圖片顯示效果:
typescript
Image($r('app.media.cat')).width(100).height(200).objectFit(ImageFit.Fill) // 設置縮放類型.fillColor(Color.Blue) // 設置SVG圖片的繪制顏色
objectFit屬性支持多種枚舉值,用于控制圖片的縮放行為:
屬性值 | 說明 |
---|---|
ImageFit.Contain | 保持寬高比進行縮小或者放大,使得圖片完全顯示在顯示邊界內 |
ImageFit.Cover | 保持寬高比進行縮小或者放大,使得圖片兩邊都大于或等于顯示邊界 |
ImageFit.Auto | 自適應顯示 |
ImageFit.Fill | 不保持寬高比進行放大縮小,使得圖片充滿顯示邊界 |
ImageFit.ScaleDown | 保持寬高比顯示,圖片縮小或者保持不變 |
ImageFit.None | 保持原有尺寸顯示 |
2. 繪制幾何圖形(Shape組件)
鴻蒙系統提供了強大的幾何圖形繪制能力,可以通過Shape組件及其子組件創建各種矢量圖形。
創建繪制組件
繪制組件可以由以下兩種形式創建:
形式一:繪制組件使用Shape作為父組件,實現類似SVG的效果。
typescript
// 創建帶有父組件的繪制組件 Shape() {Rect().width(300).height(50)Circle({ width: 150, height: 150 }).fill('red') }
形式二:繪制組件單獨使用,直接在頁面上繪制指定圖形。
typescript
// 單獨使用繪制組件 Circle({ width: 150, height: 150 })
鴻蒙提供了7種基本繪制類型:Circle(圓形)、Ellipse(橢圓形)、Line(直線)、Polyline(折線)、Polygon(多邊形)、Path(路徑)、Rect(矩形)。
形狀視口viewport
Shape組件支持viewport屬性,用于指定用戶空間中的一個矩形,該矩形映射到為關聯的SVG元素建立的視區邊界。
typescript
Shape() {Rect().width(300).height(50) } .viewPort({x: 0,y: 0,width: 300,height: 100, })
viewport屬性包含四個可選參數:
-
x?和?y:表示視區的左上角坐標
-
width?和?height:表示視區尺寸
通過viewport可以實現圖形的放大與縮小效果:
typescript
// 通過viewport對圖形進行放大與縮小 Row({space:10}) {Column() {// 放大效果Shape() {Rect().width('100%').height('100%').fill('#0097D4')Circle({width: 75, height: 75}).fill('#E87361')}.viewPort({x: 0, y: 0, width: 75, height: 75}).width(150).height(150)}Column() {// 縮小效果Shape() {Rect().width('100%').height('100%').fill('#BDDB69')Circle({width: 75, height: 75}).fill('#E87361')}.viewPort({x: 0, y: 0, width: 300, height: 300}).width(150).height(150)} }
自定義樣式
繪制組件支持多種屬性來自定義樣式:
typescript
// 設置填充顏色 Path().width(100).height(100).commands('M150 0 L300 300 L0 300 Z').fill("#E87361")// 設置邊框顏色 Path().width(100).height(100).fillOpacity(0).commands('M150 0 L300 300 L0 300 Z').stroke(Color.Red)// 設置邊框透明度 Path().width(100).height(100).fillOpacity(0).commands('M150 0 L300 300 L0 300 Z').stroke(Color.Red).strokeWidth(10).strokeOpacity(0.2)// 設置線條拐角樣式 Polyline().width(100).height(100).fillOpacity(0).stroke(Color.Red).strokeWidth(8).points([[20, 0], [0, 100], [100, 90]]).strokeLineJoin(LineJoinStyle.Round) // 圓角連接// 設置斜接長度與邊框寬度比值 Polyline().width(100).height(100).fillOpacity(0).stroke(Color.Red).strokeWidth(10).points([[20, 0], [20, 100], [100, 100]]).strokeLineJoin(LineJoinStyle.Miter) // 尖角連接.strokeMiterLimit(1/Math.sin(45)) // 設置比值
3. 使用畫布繪制自定義圖形(Canvas組件)
對于更復雜的繪圖需求,鴻蒙提供了Canvas組件,允許開發者進行完全自定義的圖形繪制。
初始化畫布組件
Canvas組件使用前需要初始化,并通過onReady事件回調進行繪制操作:
typescript
// 配置CanvasRenderingContext2D對象參數 private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)// 初始化畫布組件 Canvas(this.context).width('100%').height('100%').backgroundColor('#F5DC62').onReady(() => {// 在onReady回調中進行繪制操作this.context.fillStyle = '#0097D4';this.context.fillRect(50, 50, 100, 100);})
畫布繪制方式
Canvas組件提供了兩種繪制方式:
方式一:直接調用CanvasRenderingContext2D對象的API進行繪制
typescript
Canvas(this.context).onReady(() =>{this.context.beginPath();this.context.moveTo(50, 50);this.context.lineTo(280, 160);this.context.stroke();})
方式二:先定義Path2D對象構造路徑,再進行繪制
typescript
Canvas(this.context).onReady(() =>{let region = new Path2D();region.arc(100, 75, 50, 0, 6.28);this.context.stroke(region);})
離屏繪制
離屏繪制(offscreen rendering)允許將渲染結果繪制到與屏幕不直接相關的緩沖區中進行處理,適用于實現陰影、模糊、遮罩等特殊效果。
typescript
// 離屏繪制示例 private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) // 創建離屏畫布上下文 private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings)Canvas(this.context).width('100%').height('100%').backgroundColor('#F5DC62').onReady(() =>{// 在離屏畫布上繪制this.offContext.strokeRect(50, 50, 200, 150);// 將離屏繪制的圖像在普通畫布上顯示let image = this.offContext.transferToImageBitmap();this.context.transferFromImageBitmap(image);})
畫布常用繪制方法
Canvas組件提供了豐富的API用于繪制各種圖形和效果:
基礎形狀繪制:
typescript
Canvas(this.context).onReady(() =>{// 繪制矩形this.context.beginPath();this.context.rect(100, 50, 100, 100);this.context.stroke();// 繪制圓形this.context.beginPath();this.context.arc(150, 250, 50, 0, 6.28);this.context.stroke();// 繪制橢圓this.context.beginPath();this.context.ellipse(150, 450, 50, 100, Math.PI * 0.25, Math.PI * 0, Math.PI * 2);this.context.stroke();})
文本繪制:
typescript
Canvas(this.context).onReady(() =>{// 繪制填充類文本this.context.font = '50px sans-serif';this.context.fillText("Hello World!", 50, 100);// 繪制描邊類文本this.context.font = '55px sans-serif';this.context.strokeText("Hello World!", 50, 150);})
漸變效果:
typescript
Canvas(this.context).onReady(() =>{// 創建徑向漸變色let grad = this.context.createRadialGradient(200,200,50, 200,200,200)// 設置漸變斷點值grad.addColorStop(0.0, '#E87361');grad.addColorStop(0.5, '#FFFFF0');grad.addColorStop(1.0, '#BDDB69');// 使用漸變色填充矩形this.context.fillStyle = grad;this.context.fillRect(0, 0, 400, 400);})
繪制圖片和圖像像素處理:
Canvas組件還支持通過drawImage方法繪制圖片,以及通過createImageData、getPixelMap、getImageData等方法進行圖像像素信息處理。
實戰示例:繪制一個簡單的自定義圖形
下面是一個綜合運用Shape和Canvas組件繪制自定義圖形的完整示例:
typescript
@Entry @Component struct CustomGraphicsExample {private settings: RenderingContextSettings = new RenderingContextSettings(true)private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)build() {Column({ space: 10 }) {// 使用Shape組件繪制幾何圖形Shape() {Circle({ width: 100, height: 100 }).fill('#E87361')Rect().width(200).height(50).fill('#0097D4')}.viewPort({ x: 0, y: 0, width: 300, height: 150 }).width(300).height(150).backgroundColor('#F5DC62')// 使用Canvas組件繪制自定義圖形Canvas(this.context).width(300).height(300).backgroundColor('#FFFFFF').onReady(() => {// 繪制矩形this.context.fillStyle = '#0097D4';this.context.fillRect(50, 50, 100, 100);// 繪制圓形this.context.beginPath();this.context.arc(200, 200, 50, 0, 6.28);this.context.fillStyle = '#E87361';this.context.fill();// 繪制文本this.context.font = '20px sans-serif';this.context.fillStyle = '#000000';this.context.fillText("HarmonyOS NEXT", 60, 250);})}.width('100%').height('100%').padding(20)} }
總結
HarmonyOS NEXT提供了豐富而強大的圖形渲染能力,從簡單的圖片顯示到復雜的自定義繪圖,都能滿足開發者的各種需求:
-
Image組件簡單易用,支持多種圖片源和顯示效果控制,適合大多數圖片展示場景。
-
Shape組件提供了聲明式的矢量圖形繪制方式,支持7種基本幾何圖形和豐富的樣式配置,適合繪制簡單的矢量圖形。
-
Canvas組件提供了底層的繪圖API,支持完全自定義的圖形繪制,適合復雜的繪圖需求和動態圖形效果。
無論是開發簡單的圖片展示功能,還是實現復雜的自定義圖形繪制,鴻蒙NEXT都能提供合適的解決方案。希望通過本文的介紹,能幫助您更好地理解和運用鴻蒙的圖形渲染能力,開發出更加美觀和功能豐富的應用。
溫馨提示:在實際開發中,請注意根據需求選擇合適的圖形渲染方式。對于簡單的靜態圖形,優先考慮使用Shape組件;對于復雜的動態圖形,再考慮使用Canvas組件。同時,使用網絡圖片時別忘了申請相應的權限。