1 /* 2 * Copyright (c) 2021 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16 #ifndef FOUNDATION_ACE_FRAMEWORKS_CORE_COMPONENTS_BASE_SCOPED_CANVAS_STATE_H 17 #define FOUNDATION_ACE_FRAMEWORKS_CORE_COMPONENTS_BASE_SCOPED_CANVAS_STATE_H 18 19 #include "core/pipeline/base/flutter_render_context.h" 20 21 namespace OHOS::Ace { 22 23 class ScopedCanvas final { 24 public: Create(RenderContext & context)25 static ScopedCanvas Create(RenderContext& context) 26 { 27 auto renderContext = AceType::DynamicCast<FlutterRenderContext>(&context); 28 if (!renderContext) { 29 LOGE("render context is null"); 30 return ScopedCanvas(nullptr); 31 } 32 auto canvas = renderContext->GetCanvas(); 33 if (!canvas) { 34 LOGE("Paint canvas is null"); 35 return ScopedCanvas(nullptr); 36 } 37 return ScopedCanvas(canvas); 38 } 39 ScopedCanvas(flutter::Canvas * canvas)40 explicit ScopedCanvas(flutter::Canvas* canvas) : canvas_(canvas) 41 { 42 if (canvas_ != nullptr) { 43 canvas_->save(); 44 } 45 } 46 ~ScopedCanvas()47 ~ScopedCanvas() 48 { 49 if (canvas_) { 50 canvas_->restore(); 51 } 52 } 53 54 // Need to check with bool function before call this function. 55 flutter::Canvas* operator->() const 56 { 57 return canvas_; 58 } 59 60 operator bool() const 61 { 62 return canvas_ != nullptr; 63 } 64 GetSkCanvas()65 SkCanvas* GetSkCanvas() 66 { 67 if (canvas_) { 68 return canvas_->canvas(); 69 } 70 return nullptr; 71 } 72 FlipHorizontal(double horizontalOffset,double drawRectWidth)73 void FlipHorizontal(double horizontalOffset, double drawRectWidth) const 74 { 75 double horizontalMoveDelta = -1.0 * (horizontalOffset + drawRectWidth / 2.0); 76 canvas_->translate(-1.0 * horizontalMoveDelta, 0.0); 77 canvas_->scale(-1.0, 1.0); 78 canvas_->translate(horizontalMoveDelta, 0.0); 79 } 80 81 private: 82 flutter::Canvas* canvas_ = nullptr; 83 84 ACE_DISALLOW_COPY_AND_MOVE(ScopedCanvas); 85 }; 86 87 } // namespace OHOS::Ace 88 89 #endif // FOUNDATION_ACE_FRAMEWORKS_CORE_COMPONENTS_BASE_SCOPED_CANVAS_STATE_H 90