From 9eb2af918fc5188f4e446d7a6f05f4fbdcd6620c Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Mon, 1 Jul 2019 15:11:44 +0800 Subject: [PATCH 1/2] improve convert draw y point calculate for 2d-tasks/issues/1378 (#1739) (#1764) * improve convert draw y point calculate for 2d-tasks/issues/1378 * update comment * improve convert draw y point calculate for android * improve convert draw y point calculate for win32 --- .../cocos2dx/lib/CanvasRenderingContext2DImpl.java | 8 ++------ .../apple/CCCanvasRenderingContext2D-apple.mm | 14 ++++---------- .../win32/CCCanvasRenderingContext2D-win32.cpp | 13 ++++++------- 3 files changed, 12 insertions(+), 23 deletions(-) diff --git a/native/cocos/platform/android/java/src/org/cocos2dx/lib/CanvasRenderingContext2DImpl.java b/native/cocos/platform/android/java/src/org/cocos2dx/lib/CanvasRenderingContext2DImpl.java index 18df00effc..cb9f701ac4 100644 --- a/native/cocos/platform/android/java/src/org/cocos2dx/lib/CanvasRenderingContext2DImpl.java +++ b/native/cocos/platform/android/java/src/org/cocos2dx/lib/CanvasRenderingContext2DImpl.java @@ -370,9 +370,7 @@ public class CanvasRenderingContext2DImpl { mTextPaint.setStyle(Paint.Style.FILL); scaleX(mTextPaint, text, maxWidth); Point pt = convertDrawPoint(new Point(x, y), text); - // Convert to baseline Y - float baselineY = pt.y - mTextPaint.getFontMetrics().descent; - mCanvas.drawText(text, pt.x, baselineY, mTextPaint); + mCanvas.drawText(text, pt.x, pt.y, mTextPaint); } private void strokeText(String text, float x, float y, float maxWidth) { @@ -383,9 +381,7 @@ public class CanvasRenderingContext2DImpl { mTextPaint.setStrokeWidth(mLineWidth); scaleX(mTextPaint, text, maxWidth); Point pt = convertDrawPoint(new Point(x, y), text); - // Convert to baseline Y - float baselineY = pt.y - mTextPaint.getFontMetrics().descent; - mCanvas.drawText(text, pt.x, baselineY, mTextPaint); + mCanvas.drawText(text, pt.x, pt.y, mTextPaint); } private float measureText(String text) { diff --git a/native/cocos/platform/apple/CCCanvasRenderingContext2D-apple.mm b/native/cocos/platform/apple/CCCanvasRenderingContext2D-apple.mm index 4b57dcadf8..618290c0a7 100644 --- a/native/cocos/platform/apple/CCCanvasRenderingContext2D-apple.mm +++ b/native/cocos/platform/apple/CCCanvasRenderingContext2D-apple.mm @@ -301,21 +301,15 @@ enum class CanvasTextBaseline { point.y += _fontSize / 2.0f; } + // Since the web platform cannot get the baseline of the font, an additive offset is performed for all platforms. + // That's why we should add baseline back again on other platforms #if CC_TARGET_PLATFORM == CC_PLATFORM_MAC - // We use font size to calculate text height, but 'drawPointAt' method on macOS is based on - // the real font height and in bottom-left position, add the adjust value to make the text inside text rectangle. - point.y += (textSize.height - _fontSize) / 2.0f; + point.y -= _font.descender; // The origin on macOS is bottom-left by default, so we need to convert y from top-left origin to bottom-left origin. point.y = _height - point.y; #else - // The origin of drawing text on iOS is from top-left, but now we get bottom-left, - // So, we need to substract the font size to convert 'point' to top-left. - point.y -= _fontSize; - - // We use font size to calculate text height, but 'drawPointAt' method on iOS is based on - // the real font height and in top-left position, substract the adjust value to make text inside text rectangle. - point.y -= (textSize.height - _fontSize) / 2.0f; + point.y -= _font.ascender; #endif return point; } diff --git a/native/cocos/platform/win32/CCCanvasRenderingContext2D-win32.cpp b/native/cocos/platform/win32/CCCanvasRenderingContext2D-win32.cpp index 303e87d7d2..6e3712883d 100644 --- a/native/cocos/platform/win32/CCCanvasRenderingContext2D-win32.cpp +++ b/native/cocos/platform/win32/CCCanvasRenderingContext2D-win32.cpp @@ -371,6 +371,8 @@ private: cocos2d::Color4F _fillStyle; cocos2d::Color4F _strokeStyle; + TEXTMETRIC _tm; + // change utf-8 string to utf-16, pRetLen is the string length after changing wchar_t * _utf8ToUtf16(const std::string& str, int * pRetLen = nullptr) { @@ -589,14 +591,11 @@ private: { point.y += _fontSize / 2.0f; } - // The origin of drawing text on win32 is from top-left, but now we get bottom-left, - // So, we need to substract the font size to convert 'point' to top-left. - point.y -= _fontSize; - // We use font size to calculate text height, but draw text on win32 is based on - // the real font height and in top-left position, substract the adjust value to make text inside text rectangle. - // check - // point.y -= (textSize.height - _fontSize) / 2.0f; + // Since the web platform cannot get the baseline of the font, an additive offset is performed for all platforms. + // That's why we should add baseline back again on other platforms + GetTextMetrics(_DC, &_tm); + point.y -= _tm.tmAscent; return point; } From 875acde9841a8f4bbc02befc269567f31f33eeda Mon Sep 17 00:00:00 2001 From: minggo Date: Tue, 2 Jul 2019 15:00:15 +0800 Subject: [PATCH 2/2] native returns unpremultiplied data (#1765) * unpremultiply alpha on ios/mac * unpremultiply alpha on Android and windows --- .../CCCanvasRenderingContext2D-android.cpp | 24 ++++ .../lib/CanvasRenderingContext2DImpl.java | 12 +- native/cocos/platform/android/jni/JniImp.cpp | 25 ++++ native/cocos/platform/android/jni/JniImp.h | 1 + .../apple/CCCanvasRenderingContext2D-apple.mm | 112 ++++++++---------- .../CCCanvasRenderingContext2D-win32.cpp | 15 ++- 6 files changed, 119 insertions(+), 70 deletions(-) diff --git a/native/cocos/platform/android/CCCanvasRenderingContext2D-android.cpp b/native/cocos/platform/android/CCCanvasRenderingContext2D-android.cpp index 9545f1f117..b9455ba494 100644 --- a/native/cocos/platform/android/CCCanvasRenderingContext2D-android.cpp +++ b/native/cocos/platform/android/CCCanvasRenderingContext2D-android.cpp @@ -4,6 +4,7 @@ #include "cocos/scripting/js-bindings/jswrapper/SeApi.h" #include "platform/android/jni/JniHelper.h" +#include "platform/android/jni/JniImp.h" #include @@ -214,12 +215,35 @@ public: return _data; } +#define CLAMP(V, LO, HI) std::min(std::max( (V), (LO) ), (HI) ) + void unMultiplyAlpha(unsigned char* ptr, ssize_t size) + { + // Android source data is not premultiplied alpha when API >= 19 + // please refer CanvasRenderingContext2DImpl::recreateBuffer(float w, float h) + // in CanvasRenderingContext2DImpl.java +// if (getAndroidSDKInt() >= 19) +// return; + + char alpha; + for (int i = 0; i < size; i += 4) + { + alpha = ptr[i + 3]; + if (alpha > 0) + { + ptr[i] = CLAMP(ptr[i] / alpha * 255, 0, 255); + ptr[i+1] = CLAMP(ptr[i+1] / alpha * 255, 0, 255); + ptr[i+2] = CLAMP(ptr[i+2] / alpha * 255, 0, 255); + } + } + } + void fillData() { jbyteArray arr = JniHelper::callObjectByteArrayMethod(_obj, JCLS_CANVASIMPL, "getDataRef"); jsize len = JniHelper::getEnv()->GetArrayLength(arr); jbyte* jbarray = (jbyte *)malloc(len * sizeof(jbyte)); JniHelper::getEnv()->GetByteArrayRegion(arr,0,len,jbarray); + unMultiplyAlpha( (unsigned char*) jbarray, len); _data.fastSet((unsigned char*) jbarray, len); //IDEA: DON'T create new jbarray every time. JniHelper::getEnv()->DeleteLocalRef(arr); } diff --git a/native/cocos/platform/android/java/src/org/cocos2dx/lib/CanvasRenderingContext2DImpl.java b/native/cocos/platform/android/java/src/org/cocos2dx/lib/CanvasRenderingContext2DImpl.java index cb9f701ac4..a6d0fc00e8 100644 --- a/native/cocos/platform/android/java/src/org/cocos2dx/lib/CanvasRenderingContext2DImpl.java +++ b/native/cocos/platform/android/java/src/org/cocos2dx/lib/CanvasRenderingContext2DImpl.java @@ -210,6 +210,14 @@ public class CanvasRenderingContext2DImpl { mBitmap.recycle(); } mBitmap = Bitmap.createBitmap((int)Math.ceil(w), (int)Math.ceil(h), Bitmap.Config.ARGB_8888); + // FIXME: in MIX 2S, its API level is 28, but can not find invokeInstanceMethod. It seems + // devices may not obey the specification, so comment the codes. +// if (Build.VERSION.SDK_INT >= 19) { +// Cocos2dxReflectionHelper.invokeInstanceMethod(mBitmap, +// "setPremultiplied", +// new Class[]{Boolean.class}, +// new Object[]{Boolean.FALSE}); +// } mCanvas.setBitmap(mBitmap); } @@ -487,10 +495,12 @@ public class CanvasRenderingContext2DImpl { private byte[] getDataRef() { // Log.d(TAG, "this: " + this + ", getDataRef ..."); if (mBitmap != null) { - final byte[] pixels = new byte[mBitmap.getWidth() * mBitmap.getHeight() * 4]; + final int len = mBitmap.getWidth() * mBitmap.getHeight() * 4; + final byte[] pixels = new byte[len]; final ByteBuffer buf = ByteBuffer.wrap(pixels); buf.order(ByteOrder.nativeOrder()); mBitmap.copyPixelsToBuffer(buf); + return pixels; } diff --git a/native/cocos/platform/android/jni/JniImp.cpp b/native/cocos/platform/android/jni/JniImp.cpp index 5e506e9d78..17725a9b73 100644 --- a/native/cocos/platform/android/jni/JniImp.cpp +++ b/native/cocos/platform/android/jni/JniImp.cpp @@ -101,6 +101,7 @@ namespace int g_height = 0; bool g_isStarted = false; bool g_isGameFinished = false; + int g_SDKInt = 0; cocos2d::Application* g_app = nullptr; @@ -127,10 +128,29 @@ Application* cocos_android_app_init(JNIEnv* env, int width, int height); extern "C" { + void getSDKInt(JNIEnv* env) + { + if (env && g_SDKInt == 0) + { + // VERSION is a nested class within android.os.Build (hence "$" rather than "/") + jclass versionClass = env->FindClass("android/os/Build$VERSION"); + if (NULL == versionClass) + return; + + jfieldID sdkIntFieldID = env->GetStaticFieldID(versionClass, "SDK_INT", "I"); + if (NULL == sdkIntFieldID) + return; + + g_SDKInt = env->GetStaticIntField(versionClass, sdkIntFieldID); + } + } + JNIEXPORT jint JNI_OnLoad(JavaVM *vm, void *reserved) { JniHelper::setJavaVM(vm); cocos_jni_env_init(JniHelper::getEnv()); + getSDKInt(JniHelper::getEnv()); + return JNI_VERSION_1_4; } @@ -647,4 +667,9 @@ bool getApplicationExited() return g_isGameFinished; } +int getAndroidSDKInt() +{ + return g_SDKInt; +} + diff --git a/native/cocos/platform/android/jni/JniImp.h b/native/cocos/platform/android/jni/JniImp.h index 81bf153f67..44739cec12 100644 --- a/native/cocos/platform/android/jni/JniImp.h +++ b/native/cocos/platform/android/jni/JniImp.h @@ -50,3 +50,4 @@ extern void setGameInfoDebugViewTextJNI(int index, const std::string& text); extern void setJSBInvocationCountJNI(int count); extern void openDebugViewJNI(); extern void disableBatchGLCommandsToNativeJNI(); +extern int getAndroidSDKInt(); diff --git a/native/cocos/platform/apple/CCCanvasRenderingContext2D-apple.mm b/native/cocos/platform/apple/CCCanvasRenderingContext2D-apple.mm index 618290c0a7..e685da0ed5 100644 --- a/native/cocos/platform/apple/CCCanvasRenderingContext2D-apple.mm +++ b/native/cocos/platform/apple/CCCanvasRenderingContext2D-apple.mm @@ -23,7 +23,6 @@ #endif #include - enum class CanvasTextAlign { LEFT, CENTER, @@ -314,7 +313,7 @@ enum class CanvasTextBaseline { return point; } --(void) fillText:(NSString*) text x:(CGFloat) x y:(CGFloat) y maxWidth:(CGFloat) maxWidth { +-(void) drawText:(NSString*)text x:(CGFloat)x y:(CGFloat)y maxWidth:(CGFloat)maxWidth isStroke:(BOOL)isStroke { if (text.length == 0) return; @@ -324,11 +323,12 @@ enum class CanvasTextBaseline { paragraphStyle.lineBreakMode = NSLineBreakByTruncatingTail; [_tokenAttributesDict removeObjectForKey:NSStrokeWidthAttributeName]; - [_tokenAttributesDict removeObjectForKey:NSStrokeColorAttributeName]; - [_tokenAttributesDict setObject:paragraphStyle forKey:NSParagraphStyleAttributeName]; - [_tokenAttributesDict setObject:[NSColor colorWithRed:_fillStyle.r green:_fillStyle.g blue:_fillStyle.b alpha:_fillStyle.a] - forKey:NSForegroundColorAttributeName]; + [_tokenAttributesDict setObject:[NSColor colorWithRed:_fillStyle.r + green:_fillStyle.g + blue:_fillStyle.b + alpha:_fillStyle.a] + forKey:NSForegroundColorAttributeName]; [self saveContext]; @@ -336,57 +336,30 @@ enum class CanvasTextBaseline { CGContextSetRGBFillColor(_context, _fillStyle.r, _fillStyle.g, _fillStyle.b, _fillStyle.a); CGContextSetShouldSubpixelQuantizeFonts(_context, false); CGContextBeginTransparencyLayerWithRect(_context, CGRectMake(0, 0, _width, _height), nullptr); - CGContextSetTextDrawingMode(_context, kCGTextFill); - - + if (isStroke) + { + CGContextSetLineWidth(_context, _lineWidth); + CGContextSetLineJoin(_context, kCGLineJoinRound); + CGContextSetTextDrawingMode(_context, kCGTextStroke); + } + else + CGContextSetTextDrawingMode(_context, kCGTextFill); NSAttributedString *stringWithAttributes =[[[NSAttributedString alloc] initWithString:text attributes:_tokenAttributesDict] autorelease]; - [stringWithAttributes drawAtPoint:drawPoint]; - CGContextEndTransparencyLayer(_context); [self restoreContext]; } +-(void) fillText:(NSString*) text x:(CGFloat) x y:(CGFloat) y maxWidth:(CGFloat) maxWidth { + [self drawText:text x:x y:y maxWidth:maxWidth isStroke:FALSE]; +} + -(void) strokeText:(NSString*) text x:(CGFloat) x y:(CGFloat) y maxWidth:(CGFloat) maxWidth { - if (text.length == 0) - return; - - NSPoint drawPoint = [self convertDrawPoint:NSMakePoint(x, y) text:text]; - - NSMutableParagraphStyle* paragraphStyle = [[[NSMutableParagraphStyle alloc] init] autorelease]; - paragraphStyle.lineBreakMode = NSLineBreakByTruncatingTail; - - [_tokenAttributesDict removeObjectForKey:NSForegroundColorAttributeName]; - - [_tokenAttributesDict setObject:paragraphStyle forKey:NSParagraphStyleAttributeName]; - [_tokenAttributesDict setObject:[NSColor colorWithRed:_strokeStyle.r - green:_strokeStyle.g - blue:_strokeStyle.b - alpha:_strokeStyle.a] forKey:NSStrokeColorAttributeName]; - - [self saveContext]; - - // text color - CGContextSetRGBFillColor(_context, _fillStyle.r, _fillStyle.g, _fillStyle.b, _fillStyle.a); - CGContextSetLineWidth(_context, _lineWidth); - CGContextSetLineJoin(_context, kCGLineJoinRound); - CGContextSetShouldSubpixelQuantizeFonts(_context, false); - CGContextBeginTransparencyLayerWithRect(_context, CGRectMake(0, 0, _width, _height), nullptr); - - CGContextSetTextDrawingMode(_context, kCGTextStroke); - - NSAttributedString *stringWithAttributes =[[[NSAttributedString alloc] initWithString:text - attributes:_tokenAttributesDict] autorelease]; - - [stringWithAttributes drawAtPoint:drawPoint]; - - CGContextEndTransparencyLayer(_context); - - [self restoreContext]; + [self drawText:text x:x y:y maxWidth:maxWidth isStroke:TRUE]; } -(void) setFillStyleWithRed:(CGFloat) r green:(CGFloat) g blue:(CGFloat) b alpha:(CGFloat) a { @@ -523,6 +496,33 @@ void CanvasGradient::addColorStop(float offset, const std::string& color) // CanvasRenderingContext2D +namespace +{ +#define CLAMP(V, LO, HI) std::min(std::max( (V), (LO) ), (HI) ) + void unMultiplyAlpha(unsigned char* ptr, ssize_t size) + { + char alpha; + for (int i = 0; i < size; i += 4) + { + alpha = ptr[i + 3]; + if (alpha > 0) + { + ptr[i] = CLAMP(ptr[i] / alpha * 255, 0, 255); + ptr[i+1] = CLAMP(ptr[i+1] / alpha * 255, 0, 255); + ptr[i+2] = CLAMP(ptr[i+2] / alpha * 255, 0, 255); + } + } + } +} + +#define SEND_DATA_TO_JS(CB, IMPL) \ +if (CB) \ +{ \ + auto& data = [IMPL getDataRef]; \ + unMultiplyAlpha(data.getBytes(), data.getSize() ); \ + CB(data); \ +} + CanvasRenderingContext2D::CanvasRenderingContext2D(float width, float height) : __width(width) , __height(height) @@ -545,8 +545,7 @@ void CanvasRenderingContext2D::recreateBufferIfNeeded() _isBufferSizeDirty = false; // SE_LOGD("CanvasRenderingContext2D::recreateBufferIfNeeded %p, w: %f, h:%f\n", this, __width, __height); [_impl recreateBufferWithWidth: __width height:__height]; - if (_canvasBufferUpdatedCB != nullptr) - _canvasBufferUpdatedCB([_impl getDataRef]); + SEND_DATA_TO_JS(_canvasBufferUpdatedCB, _impl); } } @@ -561,11 +560,7 @@ void CanvasRenderingContext2D::fillRect(float x, float y, float width, float hei { recreateBufferIfNeeded(); [_impl fillRect:CGRectMake(x, y, width, height)]; - - if (_canvasBufferUpdatedCB != nullptr) - { - _canvasBufferUpdatedCB([_impl getDataRef]); - } + SEND_DATA_TO_JS(_canvasBufferUpdatedCB, _impl); } void CanvasRenderingContext2D::fillText(const std::string& text, float x, float y, float maxWidth) @@ -577,8 +572,7 @@ void CanvasRenderingContext2D::fillText(const std::string& text, float x, float recreateBufferIfNeeded(); [_impl fillText:[NSString stringWithUTF8String:text.c_str()] x:x y:y maxWidth:maxWidth]; - if (_canvasBufferUpdatedCB != nullptr) - _canvasBufferUpdatedCB([_impl getDataRef]); + SEND_DATA_TO_JS(_canvasBufferUpdatedCB, _impl); } void CanvasRenderingContext2D::strokeText(const std::string& text, float x, float y, float maxWidth) @@ -589,9 +583,7 @@ void CanvasRenderingContext2D::strokeText(const std::string& text, float x, floa recreateBufferIfNeeded(); [_impl strokeText:[NSString stringWithUTF8String:text.c_str()] x:x y:y maxWidth:maxWidth]; - - if (_canvasBufferUpdatedCB != nullptr) - _canvasBufferUpdatedCB([_impl getDataRef]); + SEND_DATA_TO_JS(_canvasBufferUpdatedCB, _impl); } cocos2d::Size CanvasRenderingContext2D::measureText(const std::string& text) @@ -634,9 +626,7 @@ void CanvasRenderingContext2D::lineTo(float x, float y) void CanvasRenderingContext2D::stroke() { [_impl stroke]; - - if (_canvasBufferUpdatedCB != nullptr) - _canvasBufferUpdatedCB([_impl getDataRef]); + SEND_DATA_TO_JS(_canvasBufferUpdatedCB, _impl); } void CanvasRenderingContext2D::fill() diff --git a/native/cocos/platform/win32/CCCanvasRenderingContext2D-win32.cpp b/native/cocos/platform/win32/CCCanvasRenderingContext2D-win32.cpp index 6e3712883d..1b2fc5f2fe 100644 --- a/native/cocos/platform/win32/CCCanvasRenderingContext2D-win32.cpp +++ b/native/cocos/platform/win32/CCCanvasRenderingContext2D-win32.cpp @@ -156,10 +156,9 @@ public: uint8_t* buffer = _imageData.getBytes(); if (buffer) { - float alpha = _fillStyle.a; - uint8_t r = _fillStyle.r * 255.0f * alpha; - uint8_t g = _fillStyle.g * 255.0f * alpha; - uint8_t b = _fillStyle.b * 255.0f * alpha; + uint8_t r = _fillStyle.r * 255.0f; + uint8_t g = _fillStyle.g * 255.0f; + uint8_t b = _fillStyle.b * 255.0f; uint8_t a = _fillStyle.a * 255.0f; fillRectWithColor(buffer, (uint32_t)_bufferWidth, (uint32_t)_bufferHeight, (uint32_t)x, (uint32_t)y, (uint32_t)w, (uint32_t)h, r, g, b, a); } @@ -558,10 +557,10 @@ private: // "dirtyValue > 0" means pixel was covered when drawing text if (dirtyValue > 0) { - // r = _fillStyle.r * 255 * (dirtyValue / 255) * alpha; - r = _fillStyle.r * dirtyValue * alpha; - g = _fillStyle.g * dirtyValue * alpha; - b = _fillStyle.b * dirtyValue * alpha; + // r = _fillStyle.r * 255 * (dirtyValue / 255); + r = _fillStyle.r * dirtyValue; + g = _fillStyle.g * dirtyValue; + b = _fillStyle.b * dirtyValue; COLORREF textColor = (b << 16 | g << 8 | r) & 0x00ffffff; val = ((BYTE)(dirtyValue * alpha) << 24) | textColor; }