Drawing on a transparent image using Java SWT

前端 未结 4 1830
天涯浪人
天涯浪人 2021-01-04 12:08

How do I create an in-memory fully transparent SWT image and draw a black line on it with antialias enabled?

I expect the result to include only black color and alph

4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-04 13:11

    To scale with transparency, I've found that I have to manually set the alpha byte array as shown below. So the alpha ends up with nearest-neighbor anti aliasing.

    public static Image scaleImage(Device device, Image orig, int scaledWidth, int scaledHeight) {
        Rectangle origBounds = orig.getBounds();
        if (origBounds.width == scaledWidth && origBounds.height == scaledHeight) {
            return orig;
        }
    
        ImageData origData = orig.getImageData();
        ImageData imData = new ImageData(scaledWidth, scaledHeight, origData.depth, origData.palette);
        if (origData.alphaData != null) {
            imData.alphaData = new byte[imData.width * imData.height];
            for (int row = 0; row < imData.height; row++) {
                for (int col = 0; col < imData.width; col++) {
                    int origRow = row * origData.height / imData.height;
                    int origCol = col * origData.width / imData.width;
                    byte origAlpha = origData.alphaData[origRow * origData.width + origCol];
                    imData.alphaData[row * imData.width + col] = origAlpha;
                }
            }
        }
        final Image scaled = new Image(device, imData);
        GC gc = new GC(scaled);
        gc.setAntialias(SWT.ON);
        gc.setInterpolation(SWT.HIGH);
        gc.setBackground(device.getSystemColor(SWT.COLOR_WHITE));
        gc.fillRectangle(0, 0, scaledWidth, scaledHeight);
        gc.drawImage(orig, 0, 0, origBounds.width, origBounds.height, 0, 0, scaledWidth, scaledHeight);
        gc.dispose();
        return scaled;
    }
    

提交回复
热议问题